定义PHP类之外的变量 [英] Define variables outside the PHP class

查看:102
本文介绍了定义PHP类之外的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我想在控制器类&访问不同的动作。

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


但它不会在索引函数中打印这个数组另一方面它在课堂外显示这个数组。



这怎么可能。
Thanks。

解决方案

要从一个方法/函数内部访问一个全局变量,必须声明它为 global ,在方法/函数中:

  class VerifierController extends SystemadminController 
{
public function indexAction()
{
global $ logInArray;
//操作主体
print_r($ logInArray);


code

$ b在手册中,请参阅 变量作用域



然而,请注意,使用全局变量并不是一个好习惯:在这种情况下,您的类不再是独立的:它依赖于外部变量的存在和正确定义 - 这是



也许解决方案是:




  • 将该变量作为参数传递给方法?

  • 或将其传递给您的类的构造函数,并将其存储在一个属性中?

  • 或添加一个方法,该方法将接收该变量,并将其存储在属性中,如果无法更改构造函数?

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.

解决方案

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 ?

这篇关于定义PHP类之外的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆