Define variables outside the PHP class

你。 提交于 2019-12-02 12:51:26

问题


I m using zend.

I want to define the below code outside the controller class & access in different Actions.

$user = new Zend_Session_Namespace('user');
$logInArray = array();
$logInArray['userId'] = $user->userid;
$logInArray['orgId'] = $user->authOrgId;

class VerifierController extends SystemadminController
{
 public function indexAction()
    {
        // action body
        print_r($logInArray);  
    }
}

But it does not print this array in index function on the other hand it show this array outside the class.

How it is possible. Thanks.


回答1:


To access a global variable from inside a method/function, you have to declare it as global, inside the method/function :

class VerifierController extends SystemadminController
{
 public function indexAction()
    {
        global $logInArray;
        // action body
        print_r($logInArray);  
    }
}


In the manual, see the section about Variable scope.


Still, note that using global variables is not quite a good practice : in this case, your class is not independant anymore : it relies on the presence, and correct definition, of an external variable -- which is bad.

Maybe a solution would be to :

  • pass that variable as a parameter to the method ?
  • or pass it to the constructor of your class, and store it in a property ?
  • or add a method that will receive that variable, and store it in a property, if you cannot change the constructor ?



回答2:


print_r($GLOBALS['logInArray']);

http://php.net/manual/en/reserved.variables.globals.php




回答3:


You can store the user in many ways and access it in more clean manner. You can store it in Zend_Registry and then use Zend_Registry::get('user') where you need to retrieve the user. You can also store it as a parameter of request object, and then in a controller simply do $user = $this->_getParam('user');

If you need access to the user array in many controllers that inherit from the SystemadminController, what you can do is store it as a protected property of the SystemadminController (eg. protected $_user). Then all you need to do in child controllers is access $this->_user.



来源:https://stackoverflow.com/questions/2505735/define-variables-outside-the-php-class

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