You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP方法兼容性报错是否为强制执行里氏替换原则(LSP)?

Is PHP's Return Type Compatibility Error Aligned with LSP?

Short answer—your code does follow the Liskov Substitution Principle (LSP), and the error you're seeing is a PHP language limitation (prior to version 7.4), not a violation of LSP.

Let's break this down step by step:

1. What LSP Actually Requires

The core rule of LSP is straightforward: anywhere a parent type is expected, a child type can be used without breaking the program's intended behavior. This means child classes must uphold all contracts the parent class defines—method signatures (in a compatible way), public APIs, and behavioral guarantees.

2. Your Code is LSP-Compliant

Looking at your example:

  • The parent General::create() returns a General instance.
  • The child Specific::create() returns a Specific instance, which is a subclass of General.

This is called covariant return typing, and it’s fully aligned with LSP. Here’s why:

  • Any code expecting a General from create() will work flawlessly with a Specific instance—since Specific inherits all of General’s methods (like doSomething()). Your incomplete doSomething(General $object) function would handle a Specific instance exactly as it would a General one, no unexpected behavior.

3. Why PHP Throws the Error

The error isn’t because you violated LSP—it’s because older PHP versions (pre-7.4) don’t support covariant return types. Before PHP 7.4, a child class’s method had to match the parent’s return type exactly, even if the child type was a valid substitute.

This was a language constraint, not a reflection of LSP rules. If you upgrade to PHP 7.4 or later, your code will run without errors—PHP added support for covariant return types (and contravariant parameter types) specifically to better align with object-oriented principles like LSP.

4. Quick LSP Validation

To confirm, let’s finish your incomplete doSomething function:

function doSomething(General $object) {
    $object->doSomething();
}

// Usage:
doSomething(General::create()); // Outputs "General speaking!"
doSomething(Specific::create()); // Outputs "Specific speaking!"

This works exactly as expected. The Specific instance replaces the General instance without breaking the function’s behavior—classic LSP in action.


内容的提问来源于stack exchange,提问作者Josef Sábl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:25:47