Home > Article > Backend Development > Detailed explanation of the function of declare in php
declareFunction in
php:
The general usage is declare(ticks=N);
Take declare(ticks=1) as an example. This sentence has two main functions. : 1. Every time the Zend engine executes a low-level statement, it executes the function
registered by register_tick_function(). can be roughly understood as executing the registered tick function every time a sentence of php code
(for example: $num=1;) is executed. One use is to control the execution time of a certain piece of code. For example, although the following code has a dead loop
at the end, the execution time will not exceed 5 seconds.
<?php declare(ticks=1); // 开始时间 $time_start = time(); // 检查是否已经超时 function check_timeout(){ // 开始时间 global $time_start; // 5秒超时 $timeout = 5; if(time()-$time_start > $timeout){ exit("超时{$timeout}秒\n"); } } // Zend引擎每执行一次低级语句就执行一下check_timeout register_tick_function('check_timeout'); // 模拟一段耗时的业务逻辑 while(1){ $num = 1; } // 模拟一段耗时的业务逻辑,虽然是死循环,但是执行时间不会超过$timeout=5秒 while(1){ $num = 1; }
<?php declare(ticks=1); pcntl_signal(SIGINT, function(){ exit("Get signal SIGINT and exit\n"); }); echo "Ctl + c or run cmd : kill -SIGINT " . posix_getpid(). "\n" ; while(1){ $num = 1; }
The above is the detailed content of Detailed explanation of the function of declare in php. For more information, please follow other related articles on the PHP Chinese website!