I have a single instance parent class, which holds ‘local global properties’, that every child class should have access to (also when it is changed)
I can think of two ways to make sure a child from an instantiated parent inherits the parent values:
1) Using static variables
class p
{
public static $var = 0;
}
class c extends p
{
function foo()
{
echo parent::$var;
}
}
$p = new p;
$c = new c;
$c->foo(); //echoes 0
p::$var = 2;
$c->foo(); //echoes 2
2) Using passed object
class p
{
public $var = 0;
}
class c extends p
{
function update_var(p $p)
{
$this->var = $p->var;
}
function foo()
{
echo $this->var;
}
}
$p = new p;
$c = new c;
$c->foo(); //echoes 0
$p->var = 2;
$c->update_var($p);
$c->foo(); //echoes 2
In my opinion the static solution is by far the most elegant one, but there might be some drawbacks, that I’m not seeing. Which solution do you believe to be the best, or is there a third better option?
(Also note, in this example the $var is public to make this example easier to illustrate, but will end up protected)
This means that you want to use static variables, since this is exactly what they were designed for.
Another option would be to use constants, but if they fit neatly in your class, that
staticis the way to goEdit: Or, you could use the pattern @true suggested if you need something a bit more complex.