[php-src] Issue #12985: Uncaught TypeError: Cannot assign null to property Person::$age of type never

From: Date: Wed, 20 Dec 2023 19:32:30 +0000
Subject: [php-src] Issue #12985: Uncaught TypeError: Cannot assign null to property Person::$age of type never
Groups: php.bugs 
Request: Send a blank email to php-bugs+get-246084@lists.php.net to get a copy of this message
Issue: https://github.com/php/php-src/issues/12985 Author: SVGAnimate ### Description Hello, > I'm trying to protect PHP's getter/setter mechanism from awkward overloading using > [never](https://www.php.net/manual/en/language.types.never.php) ```PHP <?php //using "public never $age" prohibits Overriding class Person { public never $age; public DateTime $birthdate; public function __construct(DateTime $birthdate=null) { $this->birthdate = $birthdate ? birthdate : new DateTime(); } public function getAge():DateInterval { $now=new DateTime(); return $now->diff($this->birthdate); } public function __get($name) { return match ($name) { "age" => $this->getAge(), }; } public function __set($name, $value) { return match ($name) { "age" => throw new Exception("Readonly property. Consider modify \$birthdate.") }; } } class JoneDoe extends Person { // /!\ prohibits Overriding /!\ //public never $age; This is without consequence //protected never $age; Fatal error: Access level to JoneDoe::$age must be public (as in class Person) //private never $age; Fatal error: Access level to JoneDoe::$age must be public (as in class Person) //public mixed $age; Fatal error: Type of JoneDoe::$age must be never (as in class Person) //public int $age; Fatal error: Type of JoneDoe::$age must be never (as in class Person) } $someone = new Person(); sleep(1); echo $someone->getAge()->format("He was just born %s seconds ago"); // output: He was just born 1 seconds ago ``` The program continues like this, and shows me that the `$age` property is always blocked / never accessible ```PHP $someone->age=null;// Fatal error: Uncaught TypeError: Cannot assign null to property Person::$age of type never ``` So far, so good Then the program continues like this: ```PHP sleep(1); echo $someone->age->format("He was just born %s seconds ago"); ``` And I get the error : ``` Fatal error: Uncaught Error: Typed property Person::$age must not be accessed before initialization ``` > Declaring ``public ?never $age=null;`` does nothing to the > program other than allowing reading and writing of $age to null. I expected __get() to be called, and get the output: ``` He was just born 2 seconds ago ``` Not you ? > never return-type indicating the function does not terminate. - never reach, My “Request Feature” : > never type indicating the property does never exist again. - never read, - never write; - What do you think ?

« previous php.bugs (#246084) next »