Answer the question
In order to leave comments, you need to log in
Passing data to an already created object?
I illustrate such an example code, which consists of 5 classes.
- The Chief class creates and returns objects and has four children. - Library
class with various methods and properties that are available for use by all subsequent ones;
- Two module classes Module and one View - displays the big picture.
error_reporting(E_ALL);
class Chief
{
private static $obs = array();
private $classes = array(
'lib' => 'Library',
'mod1' => 'Module1',
'mod2' => 'Module2',
'view' => 'View',
);
public function __get($name)
{
// Определение имени классов в которых вызываются не определенные свойства
$descendantClassName = get_class($this);
echo $descendantClassName . '<br>';
// Если объект уже существует, возвращаем его
if(isset(self::$obs[$name]))
{
return(self::$obs[$name]);
}
// Определяем имя нужного класса
$class = $this->classes[$name];
// Сохраняем для будущих обращений к нему
self::$obs[$name] = new $class();
// Возвращаем созданный объект
return self::$obs[$name];
}
}
class Library extends Chief
{
// Свойства и методы библиотеки выполняющие что-либо, созданные для примера
public $prop_1;
public $prop_2;
public $prop_3;
public function __construct(){}
public function toolA(){}
public function toolB(){}
public function toolC(){}
}
class Module1 extends Chief
{
public function perf()
{
$this->lib->toolA();
$m2 = new Module2();
return $this->lib->prop_3 = $m2->perf();
}
}
class Module2 extends Chief
{
public function perf()
{
return $this->lib->toolC();
}
}
class View extends Chief
{
public function perf(){
$this->lib->toolB();
$content = new Module1();
$content->perf();
$this->lib->prop_1;
}
}
$res = new View();
print $res->perf();
Answer the question
In order to leave comments, you need to log in
If the question arises which object spawned the current object, then you clearly have something wrong with the application structure. This behavior is contrary to the basic requirements of OOP.
If you REALLY need it, check the box:
"I am aware that I am doing kaku, but I really, really need it!" [ ]
and follow the secret curve path link , and read here too.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question