Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

oop - Why is overriding method parameters a violation of strict standards in PHP?

I know there are a couple of similar questions here in StackOverflow like this question.

Why is overriding method parameters a violation of strict standards in PHP? For instance:

class Foo
{
    public function bar(Array $bar){}
}

class Baz extends Foo
{
    public function bar($bar) {}
}

Strict standards: Declaration of Baz::bar() should be compatible with that of Foo::bar()

In other OOP programming languages you can. Why is it bad in PHP?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In OOP, SOLID stands for Single responsibility, Open-closed, Liskov substitution, Interface segregation and Dependency inversion.

Liskov substitution principle states that, in a computer program, if Bar is a subtype of Foo, then objects of type Foo may be replaced with objects of type Bar without altering any of the desirable properties of that program (correctness, task performed, etc.).

In strong-typed programming languages, when overriding a Foo method, if you change the signature in Bar, you are actually overloading since the original method and the new method are available with different signatures. Since PHP is weak typed, this is not possible to achieve, because the compiler can't know which of the methods you are actually calling. (hence the reason you can't have 2 methods with the same name, even if their signatures are different).

So, to avoid the violation of Liskov Substituition principle, a strict standard warning is issued, telling the programmer something might break due to the change of the method signature in the child class.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...