蛋糕PHP应用程序控制器后过滤器变量继承的怪异


CakePHP AppController afterFilter variable inheritance weirdness

我不明白为什么应用程序控制器中的变量没有更改。我有一个AppController的子类,在操作方法中,我正在更改AppController的变量。但是,这不会反映在 afterFilter 中。

这是 CakePHP 的应用控制器

<?php
class AppController extends Controller {
    var $xxxx;
    function beforeFilter()
    {
        $this->xxxx = 'this should be changed';
    }
    function afterFilter()
    {
        var_dump($this->xxxx);
        exit;
    }

}
?>

这是我的用户控制器

<?php
class UsersController extends AppController {

    function view( $id )
    {
        echo "From the AppController: {$this->xxxx} 'n";
        $this->xxxx = 'with this';
    }
}
?>

这是我运行它时的输出:

From the AppController: this should be changed
string 'this should be changed' (length=22)

我期待这个:

From the AppController: this should be changed
string 'with this' (length=9)

你知道它为什么会这样吗?任何指示如何正确执行此操作?

你应该

使用 beforeRender() 而不是 afterFilter()。

请求生命周期回调肯定会帮助您实现相同的目标。

请询问它是否对您不起作用。