I'd like to know why, how and when to use ticks in PHP:
declare(ticks=1);
// A function called on each tick event
function tick_handler()
{
echo "tick_handler() called\n";
}
register_tick_function('tick_handler');
$a = 1;
if ($a > 0) {
$a += 2;
print($a);
}
The tick function is unlike other lifecycle functions in that you can call it any time, not just when the component first initialises. It returns a promise that resolves as soon as any pending state changes have been applied to the DOM (or immediately, if there are no pending state changes).
The declare keyword sets an execution directive for a block of code. If the declare statement is not followed by a block then the directive applies to the rest of the code in the file. There are three directives which can be declared: ticks , encoding and strict_types .
One use was outlined by [email protected]:
As Chris already noted, ticks doesn't make your script multi-threaded, but they are still great. I use them mainly for profiling - for example, placing the following at the very beginning of the script allows you to monitor its memory usage:
<?php function profiler($return=false) { static $m=0; if ($return) return "$m bytes"; if (($mem=memory_get_usage())>$m) $m = $mem; } register_tick_function('profiler'); declare(ticks=1); /* Your code here */ echo profiler(true); ?>
This approach is more accurate than calling memory_get_usage only in the end of the script. It has some performance overhead though :)
Another use was described by [email protected]:
as i read about ticks the first time i thought "wtf, useless crap" - but then i discovered some usefull application...
you can declare a tick-function which checks each n executions of your script whether the connection is still alive or not, very usefull for some kind of scripts to decrease serverload
<?php function check_connection() { if (connection_aborted()) { // do something here, e.g. close database connections // (or use a shutdown function for this exit; } } register_tick_function("connection"); declare (ticks=20) { // put your PHP-Script here // you may increase/decrease the number of ticks } ?>
Ticks can be used for basic things like:
In PHP 4 you could use ticks to implement exception-like error handling.
Ticks can be used for other things too, like implementing an event driven application (e.g. a game).
A tick is an event that occurs for every N
low-level statements executed by the parser within the declare
block. The value for N
is specified using ticks=N
within the declare blocks's directive section.
The event(s) that occur on each tick are specified using the register_tick_function()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With