【问题标题】:CakePHP Set Value in Before FilterCakePHP 在过滤器前设置值
【发布时间】:2011-11-04 07:06:45
【问题描述】:

我正在使用 Cakephp1.3,我正在尝试在 beforeFilter 函数下的 app_controller.php 中设置值,这是我的代码。

function beforeFilter() {

  $sess =  $this->Session->read();

  if(isset($sess['Auth']['User'])) {
  $checkLogin = 1; 
  }
  else { $checkLogin=0; }

  $this->set('checkLogin',$checkLogin);

  //$this->Auth->authorize = 'actions';        
  $this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');        
  $this->Auth->loginRedirect = array('controller' => 'users', 'action' => 'index');
  $this->Auth->logoutRedirect = array('controller' => 'users', 'action' => 'login');        
 }

现在我想访问 user_controller.php 中的 Checklogin 值

我试过了

function beforeFilter() {
    parent::beforeFilter();
     echo $checkLogin; exit;
    $this->Auth->allow(array('users' => 'login'));
    $this->Auth->authorize = 'controller';

     } 

我收到了这个错误

未定义变量::checklogin()

请告诉我解决方法

提前致谢

【问题讨论】:

    标签: php cakephp


    【解决方案1】:

    您必须使用实例变量而不是本地变量。而不是

    $checkLogin
    

    使用

    $this->checkLogin
    

    在两个控制器中都可以使用。

    例子:

    class AbstractUser{
        function __construct(){
            $this->instanceVar = true;
            $localVar = true;
        }
    }
    
    
    class User extends AbstractUser{
        function __construct(){
            parent::__construct();
        }
    
        function useVariables(){
            var_dump(isset($this->instanceVar));  # returns true
            var_dump(isset($localVar));           # returns false
        }
    }
    
    $user = new User;
    
    $user->useVariables();
    

    编辑

    更新了示例,使其更像您的用例。

    【讨论】:

    • 全球不是这里的正确答案。在您的 AppController 中设置 $this->checkLogin = 1,在您的 UserController 中,您可以在 parent::beforeFilter() 调用之后将其与 $this->checkLogin 一起使用。在这种情况下,提到的变量范围文档不会为您提供任何帮助,您需要阅读Classes and Objects
    【解决方案2】:

    你不能访问checkLogin,除非你把它变成一个全局变量。检查variable scope 在 PHP 中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-18
      • 1970-01-01
      相关资源
      最近更新 更多