【问题标题】:Known Bug in PHP 7.3.x with Singleton Subclassing?带有单例子类化的 PHP 7.3.x 中的已知错误?
【发布时间】:2021-06-11 13:40:51
【问题描述】:

使用单例子类化,我得到了一个

致命错误:声明 TheChild::getInstance(): TheChild must be compatible with TheParent::getInstance(): TheParent in ..\test.php on line 36

使用 PHP 7.4.x NTS x64 一切正常。
使用 PHP 8.0.x NTS x64 也很好。
PHP 7.3.x NTS x64 是坏孩子。

这是我的代码:

error_reporting(E_ALL);

class TheParent {
    private static $instance;

    private function __construct() {
        // ...
    }

    public static function getInstance(): self {
        if (self::$instance == null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
}

class TheChild extends TheParent {
    private static $instance;

    private function __construct() {
        parent::__construct();
        // ...
    }

    public static function getInstance(): self {
        if (self::$instance == null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
}

我只是不确定,我在这里遗漏了一些东西......有人有什么见解吗?客户使用的是 7.3.x,所以我坚持。

【问题讨论】:

    标签: php singleton subclassing


    【解决方案1】:

    不是错误...

    PHP 7.4 引入了(完全)对协变返回类型(也是逆变参数,但这超出了您的问题范围)的支持。 https://www.php.net/manual/en/language.oop5.variance.php

    父类中的self 与子类中的self 不同,这就是为什么它在PHP 7.3(及以下)中不起作用,但它在7.4(及更高版本)中起作用,因为上述协方差(子类的self 是父类self 的更具体版本)。


    话虽如此,在子类中没有必要重复getInstance()方法,所以这不是一个实际的问题。


    此外,您可能还想了解后期静态绑定:https://www.php.net/manual/en/language.oop5.late-static-bindings.php

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-07
      相关资源
      最近更新 更多