gpt4 book ai didi

php - register_shutdown_function 覆盖

转载 作者:可可西里 更新时间:2023-11-01 13:13:44 26 4
gpt4 key购买 nike

是否可以覆盖已经设置的 register_shutdown_function 堆栈?像这样的东西:

function f1(){
echo "f1";
}
function f2(){
echo "f2";
}
register_shutdown_function("f1");
echo "actions here";
register_shutdown_function("f2");
call_to_undefined_function(); // to "produce" the error

在这种情况下,我希望脚本只调用 f2()。这可能吗?

最佳答案

你不能直接做,但总有一个解决方法:

$first = register_cancellable_shutdown_function(function () {
echo "This function is never called\n";
});

$second = register_cancellable_shutdown_function(function () {
echo "This function is going to be called\n";
});

cancel_shutdown_function($first);

输出:

$ php test.php
This function is going to be called

The code :

function register_cancellable_shutdown_function($callback)
{
return new cancellable_shutdown_function_envelope($callback);
}

function cancel_shutdown_function($envelope)
{
$envelope->cancel();
}

final class cancellable_shutdown_function_envelope
{
private $callback;

public function __construct($callback)
{
$this->callback = $callback;
register_shutdown_function(function () {
$this->callback && call_user_func($this->callback);
});
}

public function cancel()
{
$this->callback = false;
}
}

关于php - register_shutdown_function 覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9431843/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com