php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #79620 Typed nullable attribute throws Fatal error
Submitted: 2020-05-22 10:08 UTC Modified: 2020-05-22 10:22 UTC
From: jiri dot fajman at designeo dot cz Assigned:
Status: Not a bug Package: *General Issues
PHP Version: 7.4.6 OS: Ubuntu 20.04
Private report: No CVE-ID: None
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: jiri dot fajman at designeo dot cz
New email:
PHP Version: OS:

 

 [2020-05-22 10:08 UTC] 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

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2020-05-22 10:10 UTC] bwoebi@php.net
-Status: Open +Status: Not a bug
 [2020-05-22 10:10 UTC] bwoebi@php.net
This works as intended. Initialize the variable upon declaration:

private ?string $x = null;
 [2020-05-22 10:18 UTC] jiri dot fajman at designeo dot cz
Thank you for your reply.

Could you please provide an example, where this behaviour without default initialization can be used? I just can't find any. Thank you.
 [2020-05-22 10:22 UTC] nikic@php.net
@jiri: Any time you use a constructor which initializes properties.
 
PHP Copyright © 2001-2022 The PHP Group
All rights reserved.
Last updated: Thu Aug 11 09:06:03 2022 UTC