2012-07-26 29 views
6

我可以重写子类中的PHP方法,并更改签名中的参数,如下所示。PHP子类可以改变重写方法的参数吗?

class theParent { 
    function myMethod($param1) { 
    // code here 
    } 
} 

class theChild extends theParent { 
    function myMethod($param1, $param2) { 
    // code here 
    } 
} 

我测试了这一点,它工作正常,并不会引发任何错误。我的问题是,这是不好的形式?还是OOP的基本原则?

如果父方法声明为抽象,则子签名不能偏离。据推测,如果你需要强制执行界面的这个方面,这是使用的机制?

+1

这孩子上课是不是第一类的子类。更何况这是无效的语法... – nickb 2012-07-26 21:49:25

+0

它被称为**重写**。如果您想阻止子类重写某个方法,请使用[final](http://php.net/manual/en/language.oop5.final.php)关键字。 – 2012-07-26 22:33:04

回答

0

只要

class theChild extends theParent { 
} 

这是OOP的一个很好的例子。

0

你所做的被称为覆盖,它没有什么不好,但如果你想让孩子类坚持父母的签名更好地使用下面的接口你应该只给出签名和子类mut实现他们正如他们宣布的那样。

interface theParent { 
     function myMethod($param1) ; 
    } 

    class theChild extends theParent { 
     function myMethod($param1) { 
     // code here 
     } 
    } 

希望它能帮助:)

相关问题