PHP Conference Japan 2024

register_tick_function

(PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8)

register_tick_function註冊一個函式,在每次 tick 時執行

說明

register_tick_function(callable $callback, mixed ...$args): bool

註冊指定的 callback 函式,以便在呼叫 tick 時執行。

參數

callback

要註冊的函式。

args

傳遞給 callback 函式的額外參數

返回值

成功時返回 true,失敗時返回 false

範例

<?php
declare(ticks=1);

// 使用函數作為回呼
register_tick_function('my_function', true);

// 使用物件->方法
$object = new my_class();
register_tick_function(array($object, 'my_method'), true);
?>

另請參閱

新增註解

使用者貢獻的註解 2 則註解

3
Carlos Granados
7 年前
一個帶有變數輸入的工作範例,用於驗證演算法的漸進分析

<?php

$n
= 1000; // 輸入大小

declare(ticks=1);

class
Counter {
private
$counter = 0;

public function
increase()
{
$this->counter++;
}

public function print()
{
return
$this->counter;
}
}

$obj = new Counter;

register_tick_function([&$obj, 'increase'], true);

for (
$i = 0; $i < 100; $i++)
{
$a = 3;
}

// unregister_tick_function([&$obj, 'increase']);
// 不確定如何註銷,您可以改用 Counter 中的靜態方法和成員。

var_dump("基本低階操作次數: " . $obj->print());

?>
0
Peter Featherstone
7 年前
由於一個實作錯誤,在 PHP 7.0 之前,declare(ticks=1) 指令會洩漏到不同的編譯單元中。這與 declare() 指令的預期行為不符,declare() 指令應該作用於每個檔案或每個作用域。

因此,PHP 5.6 和 PHP 7.0 的實作方式不同,PHP 7.0 中已加入正確的實作。這表示以下腳本將會返回不同的結果

#index.php

<?php

declare(ticks=1);
$count = 0;

register_tick_function('ticker');
function
ticker() {
global
$count;
$count++;
}

?>

#inc.php

<?php

$baz
= "baz";
$qux = "qux";

?>

在終端機執行 php index.php 會得到

PHP 5.6 - 7
PHP 7.0 - 5
To Top