class parent
{
public function methodInParentClass()
{
echo "In parent class called from child class of:";
}
}
class childOne extends parent
{
public $childProperty = "in childOne property";
}
class childTwo extends parent
{
public $childProperty = "in childTwo property";
}
好的,所以我们有 2 个子类都扩展了一个父类。 现在,如果我打电话
childTwo->methodInParentClass()
问题:
1(methodInParentClass如何确定哪个类在调用它? 请注意:无法通过变量传入名称。
2(如果#1是可以实现的,我该如何调用孩子的类属性? 我可以实例化一个新类,然后从中调用它,但是这不会有一些性能问题(特别是因为我的项目可能会做很多事情(?
提前感谢!
你的问题,实际上,没有什么意义。让我解释一下:
1(是的,您可以使用父方法中调用的get_class($this)
来确定当前类:
public function methodInParentClass()
{
echo "In parent class called from child class of:".get_class($this);
}
2((这就是为什么我怀疑这种感觉(。请注意,当调用某个方法时,例如,当您发布$childTwo->methodInParentClass()
时,其中$childTwo
是类childTwo
的实例 - 您将使用childTwo
上下文执行此操作。因此,所有"子"属性都将是当前实例的属性,即可通过$this
变量访问。