2011-06-06 20 views
2

如何防止在foo類中創建以下something方法?如何不允許在PHP中定義子類方法

class fooBase{ 

    public function something(){ 

    } 
} 

class foo extends fooBase{ 

    public function __construct(){ 
    echo $this->something(); // <- should be the parent class method 
    } 

    public function something(){ 
    // this method should not be allowed to be created 
    } 
} 

回答

10

使用final關鍵字(象Java等):

class fooBase{ 

    final public function something(){ 

    } 
} 

class foo extends fooBase{ 

    public function __construct(){ 
    echo $this->something(); // <- should be the parent class method 
    } 

    public function something(){ 
    // this method should not be allowed to be created 
    } 
} 

PHP Final keyword。請注意0​​仍然有一個方法something,但something將只來自fooBasefoo不能覆蓋它。

+1

可以'__construct'方法是最終的太(如果fooBase有一個)? – Alex 2011-06-06 08:18:19

+2

是的,__construct可以是最終的。如果你說在父母課堂上是最終的,你就不能在孩子身上有一個。 – SamT 2011-06-06 08:26:33

+0

事實上,正如SamT所說,你可以最終做出__construct。 – MGwynne 2011-06-06 08:37:10

2

使用final關鍵字。

在你的父母:

final public function something() 
2

您可以使用final,以防止被覆蓋的基礎方法。

class fooBase{ 

    final public function something(){ 

    } 
} 
相關問題