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

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

问题描述

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

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

class Foo{公共函数栏(数组 $bar){}}类 Baz 扩展了 Foo{公共功能栏($bar){}}

<块引用>

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

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

解决方案

在 OOP 中,SOLID 代表单一职责、开闭、Liskov 替换、接口隔离和依赖倒置.

Liskov 替换 原则指出,在计算机程序中,如果 BarFoo 的子类型,那么 Foo 类型的对象可以替换为 Bar 类型的对象,而不会改变任何想要的属性该程序(正确性、执行的任务等).

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

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

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?

解决方案

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.

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

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