PHP declare Statement


Introduction

Syntax of declare statement in PHP is similar to other flow control structures such as while, for, foreach etc.

Syntax

declare (directive)
{
   statement1;
   statement2;
   . .
}

Behaviour of the block is defined by type of directive. Three types of directives can be provided in declare statement - ticks, encoding and strict_types directive.

ticks directive

A tick is a name given to special event that occurs a certain number of statements in the script are executed. These statements are internal to PHP and roughky equal to the statements in your script (excluding conditional and argument expressions. Any function can be associated with tick event by register_tick_function. Registered function will be executed after specified number of ticks in declare directive.

In following example, myfunction() is executed every time the loop in declare construct completes 5 iterations.

Example

 Live Demo

<?php
function myfunction(){
   echo "Hello World
"; } register_tick_function("myfunction"); declare (ticks=5){    for ($i=1; $i<=10; $i++){       echo $i."
";    } } ?>

Output

This will produce following result when above script is run from command line −

1
2
3
4
5
Hello World
6
7
8
9
10
Hello World

PHP also has unregister_tick_function() to remove association of a function with tick event

strict_types directive

PHP being a weakly typed language, tries to convert a data type suitably for performing a certain operation. If there is a function with two integer arguments and returns their addition, and either argument is given as float while calling it, PHP parser will automatically convert float to integer. If this coercion is not desired, we can specify strict_types=1 in declare construct

Example

 Live Demo

<?php
//strict_types is 0 by default
function myfunction(int $x, int $y){
   return $x+$y;
}
echo "total=" . myfunction(1.99, 2.99);
?>

Float parameters are coerced in integer to perform addition to give following result −

Output

total=3

However, using delcare construct with strict_types=1 prevents coercion

Example

 Live Demo

<?php
declare (strict_types=1);
function myfunction(int $x, int $y){
   return $x+$y;
}
echo "total=" . myfunction(1.99, 2.99);
?>

Output

This will generate following error −

Fatal error: Uncaught TypeError: Argument 1 passed to myfunction() must be of the type integer, float given, called in line 7 and defined in C:\xampp\php\testscript.php:3

Encoding directive

The declare construct has Encoding directive with which it is possible to specify encoding scheme of the script

Example

<?php
declare(encoding='ISO-8859-1');
echo "This Script uses ISO-8859-1 encoding scheme";
?>

Updated on: 18-Sep-2020

411 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements