2013-08-28 33 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(); 

在你的情況,這將是: 父::更新();