php 使类中的每个函数都可以访问全局变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/519078/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 22:57:48  来源:igfitidea点击:

Making a global variable accessible for every function inside a class

phpclassfunctionvariablesglobal

提问by atomicharri

I have a variable on the global scope that is named ${SYSTEM}, where SYSTEM is a defined constant. I've got a lot of classes with functions that need to have access to this variable and I'm finding it annoying declaring global ${SYSTEM};every single time.

我在全局范围内有一个名为 的变量${SYSTEM},其中 SYSTEM 是定义的常量。我有很多类的函数需要访问这个变量,我发现global ${SYSTEM};每次声明都很烦人。

I tried declaring a class variable: public ${SYSTEM} = $GLOBALS[SYSTEM];but this results in a syntax error which is weird because I have another class that declares class variables in this manner and seems to work fine. The only thing I can think of is that the constant isn't being recognised.

我尝试声明一个类变量:public ${SYSTEM} = $GLOBALS[SYSTEM];但这会导致语法错误,这很奇怪,因为我有另一个类以这种方式声明类变量并且似乎工作正常。我唯一能想到的是常量未被识别。

I have managed to pull this off with a constructor but I'm looking for a simpler solution before resorting to that.

我已经设法用构造函数解决了这个问题,但在诉诸那个之前我正在寻找一个更简单的解决方案。



EDITThe global ${SYSTEM} variable is an array with a lot of other child arrays in it. Unfortunately there doesn't seem to be a way to get around using a constructor...

编辑全局 ${SYSTEM} 变量是一个数组,其中包含许多其他子数组。不幸的是,似乎没有办法绕过使用构造函数......

回答by frglps

Ok, hopefully I've got the gist of what you're trying to achieve

好的,希望我已经了解了您要实现的目标

<?php
    // the global array you want to access
    $GLOBALS['uname'] = array('kernel-name' => 'Linux', 'kernel-release' => '2.6.27-11-generic', 'machine' => 'i686');

    // the defined constant used to reference the global var
    define(_SYSTEM_, 'uname');

    class Foo {

        // a method where you'd liked to access the global var  
        public function bar() {
            print_r($this->{_SYSTEM_});
        }

        // the magic happens here using php5 overloading
        public function __get($d) {
            return $GLOBALS[$d];  
        }

    }

    $foo = new Foo;
    $foo->bar();

?>

回答by Syntax

This is how I access things globally without global.

这就是我在没有全局的情况下全局访问事物的方式。

class exampleGetInstance 
{

private static $instance;

public $value1;
public $value2;


private function initialize() 
{
    $this->value1 = 'test value';
    $this->value2 = 'test value2';

}

public function getInstance()
{
    if (!isset(self::$instance))
    {
        $class = __CLASS__;
        self::$instance = new $class();
        self::$instance->initialize();
    }
    return self::$instance;
}

}

$myInstance = exampleGetInstance::getInstance();

echo $myInstance->value1;

$myInstanceis now a reference to the instance of exampleGetInstanceclass.

$myInstance现在是对exampleGetInstance类实例的引用。

Fixed formatting

固定格式

回答by PolyThinker

You could use a constructor like this:

您可以使用这样的构造函数:

class Myclass {
  public $classvar; 
  function Myclass() {
    $this->classvar = $GLOBALS[SYSTEM];
  }
}

EDIT: Thanks for pointing out the typo, Peter!

编辑:感谢指出错别字,彼得!

This works for array too. If assignment is not desired, taking the reference also works:

这也适用于数组。如果不需要分配,则参考也有效:

$this->classvar =& $GLOBALS[SYSTEM];

EDIT2: The following code was used to test this method and it worked on my system:

EDIT2:以下代码用于测试此方法,它在我的系统上工作:

<?php
define('MYCONST', 'varname');
$varname = array("This is varname", "and array?");

class Myclass {
  public $classvar;
  function Myclass() {
    $this->classvar =& $GLOBALS[MYCONST];
  }
  function printvar() {
    echo $this->classvar[0]; 
    echo $this->classvar[1];
  }
};

$myobj = new Myclass;
$myobj->printvar();
?>

回答by too much php

You're trying to do something really out-of-the-ordinary here, so you can expect it to be awkward. Working with globals is never pleasant, especially not with your dynamic name selection using SYSTEMconstant. Personally I'd recommend you use $GLOBALS[SYSTEM]everywhere instead, or ...

你试图在这里做一些非常不寻常的事情,所以你可以预料它会很尴尬。使用全局变量永远不会令人愉快,尤其是使用SYSTEM常量进行动态名称选择时更是如此。我个人建议你$GLOBALS[SYSTEM]在任何地方使用,或者......

$sys = $GLOBALS[SYSTEM];

... if you're going to use it alot.

...如果你要经常使用它。

回答by phihag

The direct specification of member variables can not contain any references to other variables (class {public $membervar = $outsidevar;}is invalid as well). Use a constructor instead.

成员变量的直接指定不能包含对其他变量的任何引用(class {public $membervar = $outsidevar;}也是无效的)。改用构造函数。

However, as you are dealing with a constant, why don't you use php's constantor class constantfacilities?

但是,当您处理常量时,为什么不使用 php 的常量类常量工具呢?

回答by Asciant

You could also try the singleton pattern, although to some degree it is frowned upon in OOP circles, it is commonly referred to as the global variable of classes.

您也可以尝试单例模式,尽管在某种程度上它在 OOP 圈子中是不受欢迎的,但它通常被称为类的全局变量。

<?php
class Singleton {

  // object instance
  private static $instance;

  // The protected construct prevents instantiating the class externally.  The construct can be
  // empty, or it can contain additional instructions...
  protected function __construct() {
    ...
  }

  // The clone and wakeup methods prevents external instantiation of copies of the Singleton class,
  // thus eliminating the possibility of duplicate objects.  The methods can be empty, or
  // can contain additional code (most probably generating error messages in response
  // to attempts to call).
  public function __clone() {
    trigger_error('Clone is not allowed.', E_USER_ERROR);
  }

  public function __wakeup() {
    trigger_error('Deserializing is not allowed.', E_USER_ERROR);
  }

  //This method must be static, and must return an instance of the object if the object
  //does not already exist.
  public static function getInstance() {
    if (!self::$instance instanceof self) { 
      self::$instance = new self;
    }
    return self::$instance;
  }

  //One or more public methods that grant access to the Singleton object, and its private
  //methods and properties via accessor methods.
  public function GetSystemVar() {
    ...
  }
}

//usage
Singleton::getInstance()->GetSystemVar();

?>

This example is slightly modified from wikipedia, but you can get the idea. Try googling the singleton pattern for more information

这个例子是从维基百科稍微修改的,但你可以理解这个想法。尝试谷歌搜索单例模式以获取更多信息

回答by Steven Surowiec

I'd say the first two things that stand out to me are:

我想说的前两件事对我来说是突出的:

  1. You don't need the brackets around the variable name, you can simply do public $system or public $SYSTEM.
  2. While PHP may not always require it it is standard practice to encapsulate non-numeric array indexes in single or double quotes in case the string you're using becomes a constant at some point.
  1. 您不需要变量名周围的括号,您可以简单地执行 public $system 或 public $SYSTEM。
  2. 虽然 PHP 可能并不总是需要它,但标准做法是将非数字数组索引封装在单引号或双引号中,以防您使用的字符串在某些时候变成常量。

This should be what you're looking for

这应该是你要找的

class SomeClass {
  public $system = $GLOBALS['system'];
}

You can also use class constants which would instead be

您还可以使用类常量来代替

class SomeClass {
  const SYSTEM = $GLOBALS['system'];
}

This can be referenced within the class with 'self::SYSTEM' and externally with 'SomeClass::SYSTEM'.

这可以在类中用“self::SYSTEM”引用,在外部用“SomeClass::SYSTEM”引用。