Hitu Bansal
Hitu Bansal

Reputation: 3137

CakePHP Set Value in Before Filter

i am using Cakephp1.3 and i am trying to set value in app_controller.php under beforeFilter Function here is my Code.

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');        
 }

Now i want to Access Checklogin value in user_controller.php

i tried this

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

     } 

i got this error

undefined variable::checklogin()

Please tell me solution for this

Thanks in advance

Upvotes: 1

Views: 3390

Answers (2)

topek
topek

Reputation: 18979

You have to use an instance variable not a local. Instead of

$checkLogin

use

$this->checkLogin

in both controllers and it will work.

Example:

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

EDIT

Updated the example to resemble more your use case.

Upvotes: 4

Young
Young

Reputation: 8356

You cannot access checkLogin unless you make it a global variable.Check variable scope in PHP.

Upvotes: 1

Related Questions