无法在PHP 5.5中使用变量变量执行函数


Unable to use variable variables to execute function in PHP 5.5

我自己和另一位开发人员都在两个独立的系统(Ubuntu和OSX)上安装了Lamp,由于一些奇怪的原因,我们内部开发的软件包不再适用于PHP 5.5(在我的情况下为5.5.9)

一个特别的领域是:

if (method_exists($this, 'hook_' . __FUNCTION__)) {
    $this->{'hook_' . __FUNCTION__}();
}

上面的代码导致了一个错误,指出名为hook_xxx的方法不存在,但是,如果我们将代码替换为:

if (method_exists($this, 'hook_' . __FUNCTION__)) {
    call_user_func(array($this, 'hook_' . __FUNCTION__));
}

它工作得很好。

更糟糕的是,这适用于PHP 5.4.33.

我刚刚花了两天时间与PHPBrew等进行交流,试图正确安装PHP 5.4.33,我认为该解决方案实际上是在试图找出它最初失败的原因。

有什么想法吗?

感谢

Gavin


我得到的错误是:

Call to undefined method LocalController::hook_index()

我所在的位置:

<?php
    class Controller
    {
        public function index() {
            echo 'Parent index called';
            if (method_exists($this, 'hook_' . __FUNCTION__)) {
                $this->{'hook_' . __FUNCTION__}();
            }
        }
    }
    class LocalController extends Controller
    {
        public function hook_index() {
            echo 'Child index called';
        }
    }

它自己的应用程序将在Controller中加载,然后如果它存在,它将在LocalController中加载。

这一切在5.4上运行良好,或者如果我将其更改为使用call_user_func,则会因以上错误而终止。

尝试进行字符串串联并在单独的步骤中调用

        $f = 'hook_' . __FUNCTION__;
        print('testing function ' . $f);
        if (method_exists($this, $f)) {
            $this->$f();
        } 
        $this->response->setOutput($this->render());