2011-11-04 52 views
1

我正在使用CakePHP1.3,并且我正试图在beforeFilter下的app_controller.php中设置值函数这里是我的代码。CakePHP在过滤前设置值

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()

请告诉我这个

感谢解决方案提前

回答

1

您不能访问checkLogin,除非您将其设为全局变量。请在PHP中查看variable scope

4

你必须使用一个实例变量不是本地人。取而代之的

$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(); 

编辑

更新的例子,更类似于你的使用情况。

+0

不,这是行不通的仍然相同的错误 –

+0

全球是不是正确的答案在这里。在你的AppController中设置'$ this-> checkLogin = 1',并且在你的UserController中,你可以在'parent :: beforeFilter()'调用后用'$ this-> checkLogin'来使用它。所提到的变量范围文档在这种情况下不提供任何帮助,您需要阅读[类和对象](http://php.net/manual/en/language.oop5.php) – topek