2013-08-28 32 views
-1

在PHP OOP中,可以通过外部引用该对象来调用对象的父级方法?PHP OOP如何从对象本身调用对象的父方法?

Class ObjectOne { 
    protected function method() { 
     // Does something simple 
    } 
} 

Class ObjectTwo extends ObjectOne { 
    protected function method() { 
     $temp = clone $this; 
     $this->change_stuff(); 
     if(parent::method()) { 
      // Do more stuff here 
      $temp->method(); 
      // This will call this method, not the parent's method. 
     } 
    } 

    protected function change_stuff() { 
     // Change this object's stuff 
    } 
} 

我不能调用父::()的方法,因为这将导致当前对象执行它的方法。 我想要$ temp的代替。

解决

我解决它写的是从类中调用parent::update()方法的另一个功能:

Class ObjectOne { 
    protected function method() { 
     // Does something simple 
    } 
} 

Class ObjectTwo extends ObjectOne { 
    protected function method() { 
     $temp = clone $this; 
     $this->change_stuff(); 
     if(parent::method()) { 
      // Do more stuff here 
      $temp->update_parent(); 
      // This will call this method, not the parent's method. 
     } 
    } 

    protected function change_stuff() { 
     // Change this object's stuff 
    } 

    protected function update_parent() { 
     return parent::update(); 
    } 
} 

回答

4

$temp->parent::update()没有意义。

为什么不只是做parent::update()再次代替$temp->parent::update();

您有一个名为update()两种方法如果调用$this->update()它会调用从一个电话从制造的物体的方法。 你可以做

parent::update(); 

这将运行update()方法ObjectOne

+0

我无法调用'parent :: update()',因为这会导致**当前对象**将其属性保存到数据库中。我想要$ temp的代替。 –

+0

不,它不会。它会调用父对象的'update()'方法,如果你做'parent :: update()' – u54r

+0

你错过了这一点。我不希望这个对象调用update()方法,无论他或父母的。我需要$ temp来调用它。 –

0

你可以调用任何父方法,使用下面的语法

parent::method_name(); 

在你的情况,这将是: 父::更新();