PHP:使变量在对象中可访问,而无需传递或使用$GLOBALS


PHP: Make variable accessible in object without passing it, or using $GLOBALS

我有一个变量,需要在整个对象树中访问。我的设计一开始可能看起来有点奇怪,但我正在尝试创建一个接口/API,它可以用尽可能少的代码行访问,并且易于配置。所以请耐心等待…

Class GrandParent{
  public function original(){
    $myVar = 'I am needed throughout this method and within the config file';
    require('config.php');
  }
}
Class Parent{
  public function passObj($obj){
     //perform actions on obj.
  }
  public function output(){
     //I really need to know the value of $myVar;
     return $stuff;
  }
}
Class Child{
  public function __construct(){
     //I really need to know the value of $myVar;
  }
}
// config.php:
$parent = new Parent();
$child = new Child();
$parent->passObj($child);
return $parent->output();
// the use case:
$grandparent = new GrandParent($myVar);
echo $grandparent->orignial();

再次强调:在这个设计中,我关注的是开发人员,他们应该能够轻松地修改配置文件(同时保持简短且仅限于必要的内容),并在Grandparent对象上调用一个方法("用例"),以获得所需的输出。整个构造对于开发人员来说应该是简单易用的。不过,一切都取决于$myVar。当然,我仍然希望能够封装每个类。

如何使配置脚本中创建的所有对象实例都可以访问$myVar

  • 在不多次传递变量的情况下(我希望配置简洁,不重复代码)
  • 不使用$GLOBALS(尽管对我来说,现在这可能是最简单/最好的解决方案…://)

您可以使用Singleton模式。

有了这种模式,你就有可能做这样的事情:

GrandParent::getInstance()->original();