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

I have a variable that I need to access throughout an object tree. My design may look sort of weird at first, but I am trying to create an interface/API, that's accessible with as few lines of code as possible, as well as easily configurable. So bear with me...

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

Again: With this design I am focusing on the developer who should be able to easily modify a config file (while keeping it short and only to the necessities) and call one method on the Grandparent Object ("the use case"), to get the desired output. The whole construct should be simple to use for a developer. Everything does depend on $myVar though. Of course I'd still like to be able to keep each class encapsulated.

How do I make $myVar accessible to all object instances created in the config script

  • Without passing the variable a bunch of times (I want to keep config short and simple, without repetitive code)
  • without using $GLOBALS (though to me it seems right now this may be the easiest/best solution... :-/ )

You could be using the Singleton pattern.

With this pattern you have the possibility to do things like this:

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