怎么做?
class A {
public anyfunction() {};
/* $B = new B(); */
/* $C = new C(); */
/* its defined there */
}
class B extends A {
function __construct() {
$this->C->func(); // <---- Showing Error Here
}
}
class C extends A {
public function func() {
echo "Hi";
}
}
我可以使用B :: func();但我想使用$ this-&gt; C-&gt; func()样式
答案 0 :(得分:0)
我不确定这里的目标是什么,但在阅读完问题后我很好奇,并决定尝试一下。对象可以包含扩展其类的另一个对象。
class A {
// You cannot just do $B = new B(); and $C = new C();.
// You also cannot have a constructor like this:
// public function __construct() {
// $this->B = new B;
// $this->C = new C;
// }
// because then your constructor becomes recursive and you get an error like:
// Fatal error: Maximum function nesting level of '256' reached, aborting!
// So, you have to pass them as constructor arguments.
public function __construct() {
// Because an A can have a B, or a C, or both, or neither, the constructor
// must be written more flexibly.
foreach (func_get_args() as $obj) {
$this->{get_class($obj)} = $obj;
}
}
}
class B extends A {
public function __construct() {
// Because you are calling the method from C in the constructor of B, you
// have to invoke the constructor of the parent class first so that your B will
// have a C to refer to.
call_user_func_array('parent::__construct', func_get_args());
if (property_exists($this, 'C'))
// Now this works.
$this->C->func(); // <---- echos 'Hi'
}
}
class C extends A {
public function func() {
echo "Hi";
}
}
然后你可以构建一个B
之类的:
$B = new B(new C);
它会说
您好
这很奇怪。