PHP方法兼容性报错是否为强制执行里氏替换原则(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 aGeneralinstance. - The child
Specific::create()returns aSpecificinstance, which is a subclass ofGeneral.
This is called covariant return typing, and it’s fully aligned with LSP. Here’s why:
- Any code expecting a
Generalfromcreate()will work flawlessly with aSpecificinstance—sinceSpecificinherits all ofGeneral’s methods (likedoSomething()). Your incompletedoSomething(General $object)function would handle aSpecificinstance exactly as it would aGeneralone, 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

