2012-10-17 158 views
2

具有以下的类层次:调用父类的子方法在PHP

class TheParent{ 

    public function parse(){ 
     $this->validate(); 
    } 

} 

class TheChild extends TheParent{ 

    private function validate(){ 
     echo 'Valid!!'; 
    } 
} 

$child= new TheChild(); 
$child->parse(); 

是什么在此是去工作的步骤顺序?

的问题是,当我跑的代码它给以下错误:

Fatal error: Call to private method TheChild::validate() from context 'TheParent' on line 4 

由于TheChild继承TheParent不应$this称为parse()被提及的$child实例,所以validate()将可见到parse()

注:
做一些研究,我发现,要解决这个问题要么使根据PHP手册this commentvalidate()功能protected,虽然我不完全理解为什么它在这方面的工作后,案件。

第二种解决方案是在父创建abstract protected方法validate()和在子覆盖它(这将是多余的)到第一溶液中作为子的protected方法可以从父存取?!!

有人可以解释继承在这种情况下如何工作?

回答

3

你对继承的想法是正确的,而不是可见性。

受保护的类可以用于继承类和父类,private只能用于它定义的实际类。

+0

嗯,所以当我在代码中调用'$ child-> parse()'时,它会在父类中运行函数'parse'并且其中的$ $ this'将引用父类实例而不是子类? – Songo

+0

只有一个实例,但从实例的角度来看,父类的私有方法根​​本不允许被调用。这是'private','protected'和'public'的确切目的和区别。 – Evert

2

私人只能由定义父类和子类的类来访问。

使用受保护的,而不是:

class TheParent{ 

    public function parse(){ 
     $this->validate(); 
    } 

} 

class TheChild extends TheParent{ 

    protected function validate(){ 
     echo 'Valid!!'; 
    } 
} 

$child= new TheChild(); 
$child->parse(); 
0

FROM PHP DOC

Visibility from other objects

Objects of the same type will have access to each others private and protected members even though they are not the same instances. This is because the implementation specific details are already known when inside those objects.

私人只能由class which definesSame object type实施例进行访问

class TheChild { 
    public function parse(TheChild $new) { 
     $this->validate(); 
     $new->validate(); // <------------ Calling Private Method of $new 
    } 
    private function validate() { 
     echo 'Valid!!'; 
    } 
} 

$child = new TheChild(); 
$child->parse(new TheChild()); 

输出

有效!!有效!

14

其他海报已经指出,mehods需要保护,以便访问它们。

我认为你应该在你的代码中多做一件事。您的基类parent依赖于在子类中定义的方法。这是糟糕的编程。改变你的代码是这样的:

abstract class TheParent{ 

    public function parse(){ 
     $this->validate(); 
    } 

    abstract function validate(); 

} 

class TheChild extends TheParent{ 

    protected function validate(){ 
     echo 'Valid!!'; 
    } 
} 

$child= new TheChild(); 
$child->parse(); 

创建一个抽象功能确保子类将肯定具备的功能validate因为一个抽象类的所有抽象函数必须从这样的类

继承来实现
+0

可惜那些真正了解OOP的人比其他人更容易被忽视。我会给出抽象函数的答案以及 – pythonian29033

+1

这是正确的答案。仅仅在孩子班级实施这个方法是不够的,并且交叉手指,希望它永远如此。确保孩子必须定义该方法是一种方法! –