【发布时间】:2015-12-08 08:43:56
【问题描述】:
这里是类结构。我希望 Observer:callme() 也可以从 Children 调用。
class Observer
{
protected callme()
{
}
}
class Parent extends Observer
{
function createChild()
{
$this->callme(); // this is OK
return new Child ($this);
}
}
class Child
{
private $this myParent;
public function __constructor ($myParent)
{
$this->myParent = $myParent;
}
public function __destroy()
{
$this->myParent->callme(); // FAIL!
}
}
那么如何使 FAIL 工作? (不公开,因为它只用于“父母”和它的“孩子”)
【问题讨论】:
-
如果要公开访问,为什么要保护它?只需按应有的方式公开即可。
-
除非您扩展父级,否则这不是子级。
-
在您的示例中,
Child与Observer和Parent不在同一个类层次结构中,因此它不能调用Observer::callme()。您的类名表明您的意思是Parent是Child的超类,但这不是代码所说的。 -
在
Parent内部实例化一个新的Child对象不会使Child成为Observer的子对象,因此受保护的方法callme()在其中不可用...