Known Bug in PHP 7.3.x with Singleton Subclassing?

Viewed 107

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.

1 Answers

Not a bug...

PHP 7.4 introduced (full) support for covariant return types (also contravariant arguments, but that's out of the scope of your question). https://www.php.net/manual/en/language.oop5.variance.php

self in the parent class is not the same as self in the child class, that is why it is not working in PHP 7.3 (and below), but it works in 7.4 (and above) because of the aforementioned covariance (self of child class is a more specific version of the parent self).


This being said, there is no need to repeat the getInstance() method in the child class, so this is not an actual problem.


Also, you will probably want to read about late static binding: https://www.php.net/manual/en/language.oop5.late-static-bindings.php

Related