Home  >  Article  >  Backend Development  >  Detailed explanation of the function of declare in php

Detailed explanation of the function of declare in php

伊谢尔伦
伊谢尔伦Original
2017-06-24 15:20:085307browse

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.

Run php timeout.php

<?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(&#39;check_timeout&#39;);
// 模拟一段耗时的业务逻辑
while(1){
   $num = 1;
}
// 模拟一段耗时的业务逻辑,虽然是死循环,但是执行时间不会超过$timeout=5秒
while(1){
   $num = 1;
}

2. declare(ticks=1); Each time a low-level statement is executed, the process will be checked to see if there are unhandled signals. The test code is as follows:
Run php signal.php Then CTL+c or kill -SIGINT PID will cause the running code to jump out of the infinite loop to run the function registered by pcntl_signal. The effect is that the script exit prints "Get signal SIGINT and exi" Exit

# ##
<?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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn