5

I notice that when I define a method as abstract, the signature of child classes needs to be compatible with it. This robs me of an opportunity to use the type checking in the child class' signature.

If I define the parent method as a concrete method with a default implementation, I can then override the parent method without complying with its interface.

In cases where a suitable default implementation exists, I am inclined to use the second approach. But am I letting myself in for trouble?

It just seems odd to me that the use of 'abstract' can be so limiting, so I want to know if I'm missing something...

Note - I see that similar questions have been asked in relation to other languages, but not so much PHP.

4

2 回答 2

7

这是一个非常广泛的问题,但简而言之:

如果您不尊重接口 - 它会创建脆弱的设计,因为即使根据定义每个孩子都应该支持所有祖先接口 - 您会破坏它,但定义不兼容的接口。

有一个很好的法律:http ://en.wikipedia.org/wiki/Liskov_substitution_principle

此外,这通常是一个迹象,表明您应该更喜欢委托而不是继承。

于 2012-09-02T23:53:39.030 回答
4

接口(或抽象类)强制与您的类保持一致。这是你和你继承的类之间的契约。当几个人编写代码并且您希望可靠地交换类时,这种一致性是关键。

于 2012-09-02T23:54:49.117 回答