PHP - register_tick_function ()

La fonction register_tick_function () peut enregistrer une fonction à exécuter à chaque tick.

Syntaxe

bool register_tick_function( callable $function [, mixed $arg [, mixed $... ]] )

La fonction register_tick_function () peut enregistrer une fonction nommée par func à exécuter quand un tick est appelé. De plus, nous pouvons passer un tableau constitué d'un objet et d'une méthode comme func. Cette fonction peut renvoyer true en cas de succès ou false en cas d'échec.

Exemple

<?php
   function myfunc($param1, $param2) {
      echo "In first tick function with params $param1 $param2\n";
   }

   function myfunc2($param1, $param2, $param3) {
      echo "In second tick function with params $param1 $param2 $param3\n";
   }

   function myfunc3($param1) {
      echo "In third tick function with params $param1\n";
   }

   register_tick_function("myfunc", "hello", "world");
   register_tick_function("myfunc2", "how", "are", "you?");
   register_tick_function("myfunc3", "goodbye!");

   declare(ticks=10);
   for($i = 0; $i < 20; ++$i) {
      echo "Hello\n";
   }
?>

Production

Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
In first tick function with params hello world
In second tick function with params how are you?
In third tick function with params goodbye!
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
In first tick function with params hello world
In second tick function with params how are you?
In third tick function with params goodbye!
Hello

Exemple

<?php
   // A function that records the time when it is called
   function profile($dump = FALSE) {
      static $profile;

      // Return the times stored in profile, then erase it
      if($dump) {
         $temp = $profile;
         unset ($profile);
         return ($temp);
      }
      $profile[] = microtime ();
   }

   // Set up a tick handler
   register_tick_function("profile");

   // Initialize the function before the declare block
   profile();

   // Run a block of code, throw a tick every 2nd statement
   declare(ticks=2) {
      for($x = 1; $x < 10; ++$x) {
         echo similar_text(md5($x), md5($x*$x)), "\n";
      }
   }
   
   // Display the data stored in the profiler
   print_r(profile(TRUE));
?>

Production

32
7
12
7
7
7
11
7
7
Array
(
    [0] => 0.19704000 1597409126
    [1] => 0.19712700 1597409126
    [2] => 0.19714900 1597409126
    [3] => 0.19716800 1597409126
    [4] => 0.19718400 1597409126
    [5] => 0.19719700 1597409126
    [6] => 0.19721400 1597409126
    [7] => 0.19723000 1597409126
    [8] => 0.19724400 1597409126
    [9] => 0.19725800 1597409126
)