Bug #79620 [Opn->Nab]: Typed nullable attribute throws Fatal error
| From: | bwoebi@php.net | Date: | Fri, 22 May 2020 10:10:40 +0000 |
| Subject: | Bug #79620 [Opn->Nab]: Typed nullable attribute throws Fatal error | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-227127@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=79620&edit=1
ID: 79620
Updated by: bwoebi@php.net
Reported by: jiri dot fajman at designeo dot cz
Summary: Typed nullable attribute throws Fatal error
-Status: Open
+Status: Not a bug
Type: Bug
Package: *General Issues
Operating System: Ubuntu 20.04
PHP Version: 7.4.6
Block user comment: N
Private report: N
New Comment:
This works as intended. Initialize the variable upon declaration:
private ?string $x = null;
Previous Comments:
------------------------------------------------------------------------
[2020-05-22 10:08:18] jiri dot fajman at designeo dot cz
Description:
------------
PHP 7.4.6
Following code throws "Typed property A::$x must not be accessed before initialization".
Expected behavior:
Method getX() returns null.
I cannot imagine any single usecase for this behavior and I consider it a serious bug leading back
to PHP 7.0 hacks for nullable types in method signature.
Note: Omitting getter method is not acceptable since accessing non existing attribute does not throw
error.
Test script:
---------------
<?php
class A {
private ?string $x;
/**
* @return string|null
*/
public function getX(): ?string
{
return $this->x;
}
/**
* @param string|null $x
*/
public function setX(?string $x): void
{
$this->x = $x;
}
}
$a = new A();
var_dump($a->getX());
Expected result:
----------------
Expected result is that var_dump prints null, not crash with fatal error
Actual result:
--------------
Fatal error:
Typed property A::$x must not be accessed before initialization
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=79620&edit=1