I have a set of 3 nested classes where the 'inner' classes are instanciated in the constructor of the 'outer' classes. In the constructors, I want to pass variables from the outer class to the inner, so the inner classes can use them:
<?php
class A
{
protected $vars = ['a_var' => 'var_from_a'];
public function __construct($context = [])
{
$this->vars = array_merge($this->vars, $context);
$this->b = new B($this->vars);
}
public function get()
{
return $this->vars['a_var'] . '<br>' . $this->b->get();
}
}
class B
{
protected $vars = ['b_var' => 'var_from_b'];
public function __construct($context = [])
{
$this->vars = array_merge($this->vars, $context);
$this->c = new C($this->vars);
}
public function get()
{
return $this->vars['a_var'] . '/' . $this->vars['b_var'] . '<br>' . $this->c->get() ;
}
}
class C
{
protected $vars = ['c_var' => 'var_from_c'];
public function __construct($context = [])
{
$this->vars = array_merge($this->vars, $context);
}
public function get()
{
return $this->vars['a_var'] . '/' . $this->vars['b_var'] . '/' . $this->vars['c_var'] . '<br>';
}
}
$a = new A();
echo $a->get();
?>
// var_from_a
// var_from_a/var_from_b
// var_from_a/var_from_b/var_from_c
So far so good, but I want to change the class method get() of class B to the following:
class B
{
/* ... */
public function get()
{
/* insertion here */
$this->vars['b_var'] = 'hurray';
/* insertion here */
return $this->vars['a_var'] . '/' . $this->vars['b_var'] . '<br>' . $this->c->get() ;
}
}
// var_from_a
// var_from_a/hurray
// var_from_a/var_from_b/var_from_c
So my question is: Is there a pattern, maybe something with referenced variables, to get this result instead:
// var_from_a
// var_from_a/hurray
// var_from_a/hurray/var_from_c
I want to change the already passed variable in class C from a method of class B.
Aucun commentaire:
Enregistrer un commentaire