how to use public variable in helper file of cakep

2019-09-01 18:26发布

问题:

I have created a helper in cakephp and defined a global variable in AppController.php file.

AppController.php

public $testVar = null;

I want to use this variable in my helper file. How can do this?

回答1:

You can't use that variable in a helper but you can either

  1. In AppController, put the variable in the session: Session::write('currentUser', $this->currentUser). You can then access it in the Helper using the SessionHelper: $this->Session->read('currentUser')

  2. Pass the variable to the view using set : $this->set('currentUser', $this->currentUser). You can then access the $currentUser variable in the view and pass it to your helper as a parameter.

As an aside, if it is the ID of the logged in user you need and you're using the Auth component, you can find all the user information in the session already. You can access it in your helper as follows: $this->Session->read('Auth.User.id')



回答2:

You don't need to pass around an extra variable. Directly access AuthComponent statically:

echo AuthComponent::user('username');

etc.

Note: This is also notice-free as it checks on the existence first (which you would need to manually assert with using arrays here.