Detailed explanation of php declare usage

藏色散人
Release: 2023-03-06 19:10:01
Original
3005 people have browsed it

php The general usage of declare is "declare(ticks=N);". Its function is that the Zend engine will execute the function registered by "register_tick_function()" every time it executes a low-level statement.

Detailed explanation of php declare usage

Recommended: "PHP Video Tutorial"

Detailed explanation of the function of declare 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 When executing a low-level statement, the function registered by register_tick_function() is executed once.

It can be roughly understood that every time a sentence of php code is executed (for example: $num=1;), the registered tick function will be executed.

One use is to control the execution time of a certain piece of code. For example, although the following code has an infinite 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;
}
Copy after login

2. declare(ticks=1); Each time a low-level statement is executed, the process will be checked for 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;
}
Copy after login

The above is the detailed content of Detailed explanation of php declare usage. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template