Declare (ticks and tick functions) Statement in PHP : Tutorial


Ticks have been deprecated as of PHP 5.3.
Ticks will be removed completely from PHP 6 onwards

declare is not a function, its a language construct. It is used for process controlling.

Syntax :
declare (directive) {
    statement 
}
There are two declare directives in PHP.

1. Ticks directive
2. Encoding directive

Tick directive

A tick is an event that occurs for every N low-level tickable statements executed by the parser within the declare block.
The value for N is specified using ticks=N within the declare block's directive section.

Tick Functions :

1. register_tick_function() : This function is used to register a handler (function) when a tick is called

Syntax :
bool register_tick_function (callable $function [, mixed $arg [, mixed $... ]])

2. unregister_tick_function () : This function is used to de-register a function so that they are no longer executed when a tick is called.

Syntax :
void unregister_tick_function (string $function_name)
void unregister_tick_function (string $function_name)
Not all statements are tickable.Condition expressions and argument expressions are not tickable.
register_tick_function() is used to register the occurrence of ticks
Example:
<?php

declare(ticks=1);

function Handler()
{
    echo "Handler called <br>";
}

register_tick_function('Handler');
echo "Hello <br>";

?>

?>
Output

Handler called Hello Handler called Handler called
Note : declare(ticks=1); is used to tells php to call tick handler for every function.
If you want to call the handler for every function you can used declare(ticks=n), where n is a numeric value.


Encoding directive

In PHP we can specify script encoding using encoding directive.
We can specify different encoding to different blocks.

Syntax :
declare(encoding=ENCODING_VALUE);

OR

declare(encoding=ENCODING_VALUE) {
	//for a block
}


Example:
<?php

declare(encoding='ISO-8859-1');
 echo "Script is encoded using ISO-8859-1";
 
?>
Output

Script is encoded using ISO-8859-1