how to use public variable in helper file of cakephp

假如想象 提交于 2019-12-13 06:02:59

问题


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.



来源:https://stackoverflow.com/questions/21230330/how-to-use-public-variable-in-helper-file-of-cakephp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!