2013-12-12 44 views
1
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"; 
} 

好的,所以我们有两个子类都扩展了父类。现在,如果我叫确定哪个子类正在调用父类'方法

childTwo->methodInParentClass() 

问题:

1)methodInParentClass如何确定是哪个类调用它?请注意:通过变量传入名称不可用。 2)如果#1是可以实现的,我怎样称呼孩子的班级资产?我可以实例化一个新类,然后从中调用它,但不会有一些性能问题(特别是因为我的项目可能会这样做很多)?

在此先感谢!

回答

2

你的问题实际上没有什么意义。让我来解释:

1)是的,你可以确定与get_class($this)调用父类的方法当前类:

public function methodInParentClass() 
{ 
    echo "In parent class called from child class of:".get_class($this); 
} 

2)(这是为什么我怀疑感)。请注意,例如,在调用某种方法时,例如,因为您已发布$childTwo->methodInParentClass(),其中$childTwochildTwo类的实例 - 您将使用childTwo上下文执行此操作。因此,所有“孩子”属性将是当前实例的属性,即可通过变量$this访问。

+0

嗯......我误读了get_class的文档,并且觉得它会返回“父”类/属性。我的错。 –