在类中访问父函数时,我发现自己正在这样做
$ this-> parent-> parent-> parent-> my_function()
是否可以使用一个函数爬上一棵类树以到达第一个主要对象?
我提供了一个示例类结构,以显示一些继承其他类的类。
<?php
class a {
public $b_classes;
public function __construct()
{
echo 'In '. __CLASS__ .' Constructor<br>';
$this->print_time();
$this->b_classes[] = new b($this);
}
public function print_time() {
print time() . "<br>";
}
}
class b {
public $c_classes, $d_classes;
public $parent;
public function __construct($parent)
{
$this->parent = $parent;
echo 'In '. __CLASS__ .' Constructor<br>';
$this->parent->print_time();
$this->c_classes[] = new c($this);
//$this->d_classes[] = new d($this);
}
}
class c {
public $parent;
public function __construct($parent)
{
$this->parent = $parent;
echo 'In '. __CLASS__ .' Constructor<br>';
$this->parent->parent->print_time();
}
}
class d extends c {
public $parent;
public function __construct()
{
$this->parent = $parent;
echo 'In '. __CLASS__ .' Constructor<br>';
}
}
$x = new a();
echo "<pre>";
print_r($x);
echo "</pre>";
?>