如何在cakephp的helper文件中使用公共变量

如何在cakephp的helper文件中使用公共变量,cakephp,controller,cakephp-2.0,helper,Cakephp,Controller,Cakephp 2.0,Helper,我在cakephp中创建了一个助手,并在AppController.php文件中定义了一个全局变量 AppController.php public $testVar = null; 我想在助手文件中使用此变量。如何做到这一点?您不能在助手中使用该变量,但也可以 在AppController中,将变量放入会话:session::write('currentUser',$this->currentUser)。然后,您可以使用SessionHelper在Helper中访问它:$this->Sess

我在cakephp中创建了一个助手,并在AppController.php文件中定义了一个全局变量

AppController.php

public $testVar = null;

我想在助手文件中使用此变量。如何做到这一点?

您不能在助手中使用该变量,但也可以

  • 在AppController中,将变量放入会话:
    session::write('currentUser',$this->currentUser
    )。然后,您可以使用SessionHelper在Helper中访问它:
    $this->Session->read('currentUser')

  • 使用set:
    $this->set('currentUser',$this->currentUser)
    将变量传递给视图。然后可以访问视图中的
    $currentUser
    变量,并将其作为参数传递给助手


  • 另外,如果它是您需要的登录用户的ID,并且您正在使用Auth组件,那么您可以在会话中找到所有用户信息。您可以在助手中访问它,如下所示:
    $this->Session->read('Auth.User.id')
    您不需要传递额外的变量。 直接静态访问AuthComponent:

    echo AuthComponent::user('username');
    
    等等


    注意:这也是免费的,因为它首先检查存在性(您需要在此处使用数组手动断言)。

    PS:如果这仍然太多而无法键入,您可以使用类似的东西将其缩减为
    Auth::user()
    。我不是在谈论Auth组件。它的问题与?在Helper中,您可以在控制器中设置()后使用
    $this->\u View->getVar('testVar')