Known Bug in PHP 7.3.x with Singleton Subclassing?

  php, singleton, subclassing

With Singleton Subclassing, I get a

Fatal error: Declaration of TheChild::getInstance(): TheChild must be compatible with TheParent::getInstance(): TheParent in ..test.php on line 36<

Using PHP 7.4.x NTS x64 all is fine.
Using PHP 8.0.x NTS x64 all fine as well.
PHP 7.3.x NTS x64 are the bad boys.

Here is my Code:

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;
    }
}

I am just not sure, that I am missing something here…Anybody any insights? Customer uses 7.3.x, so I am stuck with that.

Source: Ask PHP

LEAVE A COMMENT