Is a property default value of null the same as no default value?

后端 未结 3 590
死守一世寂寞
死守一世寂寞 2021-01-17 07:43

And can I therefore safely refactor all instances of

class Blah
{
    // ...
    private $foo = null;
    // ...
}

to

class         


        
3条回答
  •  再見小時候
    2021-01-17 08:06

    Apart from the accepted answer that is still true, with the addition of typed properties in PHP 7.4 there are new things to consider.

    Given the following code

    class A {
        public ?DateTime $date;
    }
    
    $a = new A();
    $a->date;
    

    You will get the error

    PHP Fatal error:  Uncaught Error: Typed property A::$date must not be accessed before initialization
    

    That means that the property $date is not automatically initialized with null even though this would be a valid value. You'll have to initialize it directly like public ?DateTime $date = null; or use the constructor to do so.

提交回复
热议问题