Re: [RFC][Discussion] Why can constructors violate LSP?

From: Date: Fri, 24 Nov 2023 12:34:14 +0000
Subject: Re: [RFC][Discussion] Why can constructors violate LSP?
References: 1  Groups: php.internals 
Request: Send a blank email to internals+get-121806@lists.php.net to get a copy of this message
Hi Robert, Am 23.11.23 um 21:31 schrieb Robert Landers:
However, we can make certain methods private anyway, namely, constructors (I haven't gone hunting for other built-in methods yet). This is perfectly allowed: class P {
     public function __construct($name = 'waldo') {
         echo "hello $name\n";
     }
} class C extends P {
     private function __construct($name = 'world') {
         parent::__construct($name);
         echo "goodbye $name\n";
     }
}
you can enforce a public constructor by using an interface:
interface X {
    public function __construct (int $foo);
}

class A implements X {
    public function __construct (int $foo) {
        echo __CLASS__ . ": $foo\n";
    }
}

class B extends A {
    private function __construct (int $foo) {
        echo __CLASS__ . ": $foo\n";
    }
}
Which will give you the following error: PHP Fatal error:  Access level to B::__construct() must be public (as in class X) in test.php on line 14 That way you put the definition of the constructor into the contract. Greets Dennis

« previous php.internals (#121806) next »