search
HomeBackend DevelopmentPHP ProblemHow to implement timer effect in PHP

PHP does not have native timer-related functions similar to setInterval or setTimeout in JS. But we can do it in other ways, such as using declare. Let me introduce the usage of declare to you.

How to implement timer effect in PHP

Let’s first take a look at how it is implemented, and then let’s learn what the declare expression is. .

function do_tick($str = '')
{
    list($sec, $usec) = explode(' ', microtime());
    printf("[%.4f] Tick.%s\n", $sec + $usec, $str);
}
register_tick_function('do_tick');

do_tick('--start--');
declare (ticks = 1) {
    while (1) {
        sleep(1); // 这里,每执行一次就去调用一次do_tick()
    }
}

This is a very simple code that will output the current time every second after running.

declare syntax is defined as follows:

declare (directive)
    statemaent;
  • declare structure is used to set the execution instruction of a piece of code

  • directive part Allows setting the behavior of declare snippets. Currently, only two instructions are known: ticks and encoding

  • Tick (clock cycle) is an event that occurs every time the interpreter executes N low-level statements that can be timed in the declare code segment. . The value of N is specified by ticks=N in the directive part of declare

  • The events that occur in each tick are specified by register_tick_function()

Here, we only study the use of ticks.

In the above code, we use register_tick_function() to register the do_tick() method for ticks, and declare specifies ticks=1, which means that every time a low-level statement that can be timed is executed, register_tick_function() will be executed. method of registration. When the while in the declare code block loops each time, there is a sleep() that pauses for one second, and this sleep() is the low-level statement that can be timed.

So, isn’t while() a low-level statement that can be timed? Of course not. Conditional judgments such as where and if are not such low-level statements that can be timed.

Not all statements can be timed. Usually conditional expressions and parameter expressions are not timeable.

Let’s take a look at how to execute the declaration step by step through the following example:

function test_tick()
{
    static $i = 0;
    echo 'test_tick:' . $i++, PHP_EOL;
}
register_tick_function('test_tick');
test_tick(); // test_tick:0

$j = 0; 
declare (ticks = 1) {
    $j++; // test_tick:1

    $j++; // test_tick: 2
    
    sleep(1); //  停1秒后,test_tick:3

    $j++; // test_tick:4

    if ($j == 3) { // 条件表达式,不会执行ticks

        echo "aa", PHP_EOL; // test_tick:5 \n   test_tick:6,PHP_EOL会计一次ticks
    }
}

// declare使用花括号后面所有代码无效果,作用域限定在花括号以内
echo "bbb"; // 
echo "ccc"; // 
echo "ddd"; //

The comments are very detailed, so we don’t need to explain them one by one. Let's look at the result of setting ticks to 2 and not using curly braces for the statemaent under declare:

function test_tick1() 
{
    static $i = 0;
    echo 'test_tick1:' . $i++, PHP_EOL;
}
register_tick_function('test_tick1');

$j = 0; // 此处不计时
declare (ticks = 2); 
$j++; // test_tick1:0 

$j++; 

sleep(1); //  停1秒后 test_tick1:1

$j++; 

$j++; // test_tick1:2

if ($j == 4) { // 条件表达式,不会执行ticks
    // echo "aa", PHP_EOL;
    echo "aa"; // test_tick:10,test_tick1不执行,没有跳两步,如果用了,PHP_EOL,那么算两步,会输出test_tick1:3
}

//  declare没有使用花括号将对后面所有代码起效果,如果是require或者include将不会对父页面后续内容进行处理
echo "bbb"; // test_tick1:3
echo "ccc";
echo "ddd"; // test_tick1:4

It can be seen that our declare has an effect on the subsequent code of its definition, but it should be noted that If there are nested pages, subsequent code on the parent page will have no effect. After defining ticks=2, the function code registered by register_tick_function() will be executed once after the two low-level timer codes.

Test code:

https://github.com/zhangyue0503/dev-blog/blob/master/php/201911/source/PHP%E6%B2%A1%E6%9C%89%E5%AE%9A%E6%97%B6%E5%99%A8%EF%BC%9F.php

Recommended learning: php video tutorial

The above is the detailed content of How to implement timer effect in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
ACID vs BASE Database: Differences and when to use each.ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PM

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

PHP Secure File Uploads: Preventing file-related vulnerabilities.PHP Secure File Uploads: Preventing file-related vulnerabilities.Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Input Validation: Best practices.PHP Input Validation: Best practices.Mar 26, 2025 pm 04:17 PM

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

PHP API Rate Limiting: Implementation strategies.PHP API Rate Limiting: Implementation strategies.Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP Password Hashing: password_hash and password_verify.PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PM

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP XSS Prevention: How to protect against XSS.PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PM

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

PHP Interface vs Abstract Class: When to use each.PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PM

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use