Bug #78904 [Opn->Nab]: Side-effects for uninitialised typed property
| From: | requinix@php.net | Date: | Tue, 03 Dec 2019 22:40:37 +0000 |
| Subject: | Bug #78904 [Opn->Nab]: Side-effects for uninitialised typed property | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-224031@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=78904&edit=1
ID: 78904
Updated by: requinix@php.net
Reported by: public at grik dot net
Summary: Side-effects for uninitialised typed property
-Status: Open
+Status: Not a bug
Type: Bug
Package: *General Issues
PHP Version: 7.4.0
Block user comment: N
Private report: N
New Comment:
Works as intended. https://wiki.php.net/rfc/typed_properties_v2
Typed properties are never initialized to a default null, unlike untyped properties. That is why $y
and $z do not show up through get_object_vars: they are uninitialized. No, it cannot simply return
null because (a) the properties do not have the value of null and (b) null may not even be a valid
value for the property.
And as happens in some other languages, accessing an uninitialized property is not allowed.
As for the fatal error,
* ->y triggers __get, which returns null, which is valid for the "?string" type. No
error.
* ->x triggers __get, which returns null, which is not valid for the "string" type.
Error.
Previous Comments:
------------------------------------------------------------------------
[2019-12-03 22:24:35] public at grik dot net
Description:
------------
Unitialized properties make unpredictabe side effects.
In fact, unitialized property is a Schrödinger property - it both exists and does not exist at
the same time.
All popular frameworks use magic getters in base classes.
Having __get() called for uninitialized properties makes initialization in declaration to be
obligatory, or face unpredictable side effects, as it was in Pascal 30 years ago.
Scripting languages were inteneded to help avoid obligatory initialization in declaration.
Test script:
---------------
<?php
abstract class Base{
public function __get($name){echo 'magic';}
}
class A extends Base{
public string $x;
public ?string $y;
public $z;
}
$A = new A;
var_dump(get_object_vars($A)); //array(0) {}
var_dump(property_exists($A,'x'));//true
$A->z; // __get is not executed
$A->y; // magic - __get() is executed
$A->x; //Fatal error
Expected result:
----------------
array(3) {
["x"]=>
NULL
["y"]=>
NULL
["z"]=>
NULL
}
bool(true)
Actual result:
--------------
array(1) {
["z"]=>
NULL
}
bool(true)
magicmagic
Fatal error: Uncaught TypeError: Typed property A::$x must be string, null used
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=78904&edit=1