为什么覆盖方法参数违反了PHP中的严格标准? [英] Why is overriding method parameters a violation of strict standards in PHP?

查看:73
本文介绍了为什么覆盖方法参数违反了PHP中的严格标准?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道StackOverflow中有几个类似的问题,例如这个问题

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

为什么覆盖方法参数违反了PHP中的严格标准? 例如:

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) {}
}

严格标准:Baz :: bar()声明应与 Foo :: bar()

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

您可以使用其他OOP编程语言.为什么在PHP中不好?

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

推荐答案

在OOP中, SOLID 代表单一责任,开放式封闭,Liskov替代,接口隔离和依赖倒置.

Liskov替换原则指出,在计算机程序中,如果 Bar Foo 的子类型,然后可以将 Foo 类型的对象替换为 Bar 类型的对象,而不会更改该程序(正确性,执行的任务等).

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.).

在强类型编程语言中,当覆盖Foo方法时,如果在Bar中更改签名,则实际上是重载,因为原始方法和新方法都具有不同的签名.由于PHP是弱类型的,因此无法实现,因为编译器无法知道您实际调用的是哪种方法. (因此,即使它们的签名不同,您也无法使用两个名称相同的方法.

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).

因此,为避免违反Liskov替换原理,会发出严格的标准警告,告知程序员由于子类中方法签名的更改而可能导致某些问题中断.

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.

这篇关于为什么覆盖方法参数违反了PHP中的严格标准?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆