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
You could be using the Singleton pattern.
With this pattern you have the possibility to do things like this:
GrandParent::getInstance()->original();