2011-06-06 100 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(){ 

    } 
}