gpt4 book ai didi

php - 为什么 PHP 允许 "incompatible"构造函数?

转载 作者:IT王子 更新时间:2023-10-29 01:18:27 28 4
gpt4 key购买 nike

这里有几个片段:

  1. 重写构造函数方法有一个额外的参数。

    class Cat {
    function __construct() {}
    }

    class Lion extends Cat {
    function __construct($param) {}
    }
  2. 覆盖(常规)方法有一个额外的参数。

    class Cat {
    function doSomething() {}
    }

    class Lion extends Cat {
    function doSomething($param) {}
    }

第一个会起作用,而第二个会抛出 Lion::doSomething() 的声明应该与 Cat::doSomething() 的声明兼容

为什么对构造方法有特殊态度?

最佳答案

要了解他们为何受到不同对待,您必须了解 Liskov's Substitution Principle , 其中 states

If for each object o1 of type S there is an object o2 of type T such that for all programs P defined in terms of T, the behavior of P is unchanged when o1 is substituted for o2 then S is a subtype of T." - BarbaraLiskov, Data Abstraction and Hierarchy, SIGPLAN Notices, 23,5 (May, 1988).

简而言之,这意味着任何使用您的 LionCat 的类都应该能够可靠地调用 doSomething ,而不管类如何是其中之一。如果您更改方法签名,则不再保证这一点(您可以扩大它,但不能缩小它)。

非常简单的例子

public function doSomethingWithFeline(Cat $feline)
{
$feline->doSomething(42);
}

由于 Lion extends Cat,您建立了 is-a 关系,这意味着 doSomethingWithFeline 将为 Cat< 接受 Lion/。现在假设您在 Lion 中向 doSomething 添加了一个必需的参数。上面的代码会中断,因为它没有传递那个新参数。因此,需要兼容的签名。

LSP does not apply to constructors不过,because subtypes might have different dependencies .例如,如果你有一个 FileLogger 和一个 DBLogger,第一个的 ctors(构造函数)需要一个文件名,而后者需要一个 db 适配器。因此,ctor 是关于具体实现的,而不是类之间契约的一部分。

关于php - 为什么 PHP 允许 "incompatible"构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15413829/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com