【问题标题】:How to Check whether the function is called for the last time in PHP如何在PHP中检查函数是否最后一次调用
【发布时间】:2010-10-03 13:22:25
【问题描述】:

我想检查一个函数是否最后一次被调用。考虑以下示例代码,

function foo(){
    if( this is the last call ) {
         echo 'this is the last call of this function';
    }
}

foo(); // should not print
foo(); // should not print
foo(); // since this is the last call, it should print

在我的项目中,我需要条件语句出现在函数中。

我有一个使用常量/全局变量/计数器的想法,但不知道如何实现。有什么想法可以检测函数的最后一次调用吗?

【问题讨论】:

  • 整个想法是错误的。手动连续调用意味着错误的代码结构。你为什么不告诉一个你想要解决的真实案例,以获得一个简单而常用的解决方案,而不是要求一个奇怪而丑陋的解决方案?
  • “有两次我被问到,'请祈祷,巴贝奇先生,如果你把错误的数字放入机器中,正确的答案会出来吗?'我无法正确理解可能引发这样一个问题的想法的混乱。” ——查尔斯·巴贝奇

标签: php function call


【解决方案1】:

如果您知道最后一次调用发生在代码中的哪个位置,您可以使用全局变量来执行此操作,例如

function foo(){
    if($GLOBALS['debug_foo']) {
         echo 'this is the last call of this function';
    }
}

$GLOBALS['debug_foo']=false;

foo(); // should not print
foo(); // should not print

$GLOBALS['debug_foo']=true;

foo(); // since this is the last call, it should print

有关更多帮助,请参阅variable scope 上的 PHP 手册页。

如果你无法在代码中知道最后一次调用是什么时候,你可以使用register_shutdown_function,例如

function shutdown()
{
    echo $GLOBALS['foo_dump'];
}

function foo()
{
    $GLOBALS['foo_dump']='record some information here';   
}

//make sure we get notified when our script ends...
register_shutdown_function('shutdown');

foo(); // should not print
foo(); // should not print
foo(); // won't print anything, but when the script ends, our
       // shutdown function will print the last captured bit
       // of diagnostic info

【讨论】:

  • 嘿,保罗,知道这样的东西可以用来做什么吗?
  • 好吧,正如您评论的那样,我们无法确切知道他要解决什么问题,但很明显他不确定 PHP 全局变量是如何工作的。所以,这可能在这方面有所帮助!
【解决方案2】:

您是否尝试过使用built-in shutdown function?

【讨论】:

    【解决方案3】:

    你试图预测未来——这是不可能的。但是,你可以模仿这个。 该函数每次都会做它的事情,你会缓存每次的结果。
    您将只使用上次的结果。
    另一方面,在 php.ini 中可能会自动将脚本附加到进程的末尾。你可以把函数调用放在那里。 (或者使用上面提到的寄存器关闭)。 最后一件事,您的设计似乎有一个严重的流程,或者您能详细说明一下吗?

    【讨论】:

      【解决方案4】:

      如果您是 PHP 新手,并且如果我正确地假设了这个程序的意图,那么持有这样的逻辑并不是最佳实践:函数在最后一次调用时自行猜测和决定。应该在更全局的范围内推动这种行为。

      例如,您可以使用布尔值

        function foo($last=false){
            if( $last ) {
                 echo 'this is the last call of this function';
            }
        }
      
        foo(); // should not print
        foo(); // should not print
        foo(true); // since this is the last call, it should print
      

      【讨论】:

        【解决方案5】:

        我真的不认为这是可能的。你无法知道最后一次通话是什么时候。

        编辑:全局变量无济于事。正如其他人所说,您正在尝试预测未来。想象一下,您决定在当天接到的最后一个电话结束时关闭手机。您无法控制谁可能会选择给您打电话或什么时候给您打电话。

        【讨论】:

        • 使用全局变量有什么好处?
        • @Aakash 有什么想法为什么你需要这么不寻常的东西?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-08
        相关资源
        最近更新 更多