如何在php中调用受保护的方法? [英] How to call a protected method in php?
问题描述
这是类结构.我也希望Observer:callme()也可以从Children那里调用.
here is the class structure. I want Observer:callme() to be callable from Children too.
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工作呢? (无需将其公开,因为它仅用于父母"及其孩子"内部)
so how to make FAIL work? (without making it public, because its only for used inside "Parent" and its "Children")
推荐答案
问题是只能从相同的类或子类中访问受保护的方法.您可以做的是从Parent扩展Child类,就像这样:
The problem is that a protected method is only accessed from the same class or the class children. What you can do is extend your Child class from Parent, like this:
class Child extends Parent
{
public function __constructor ()
{
parent::__constructor();
}
public function __destroy()
{
$this->callme(); // Should work!
}
}
或者只是将方法更改为public.
Or just change the method to public.
顺便说一句,这段代码是您将要使用的某种真实代码吗?那个接收父对象的构造函数似乎是错误的.您想完成什么?
And, btw, is this code some kind of real code that you will use? That constructor receiving the parent object seems to be so wrong. What are you trying to accomplish?
这篇关于如何在php中调用受保护的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!