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

后端 未结 3 602
死守一世寂寞
死守一世寂寞 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:20

    Untyped properties

    Simple answer, yes. See http://php.net/manual/en/language.types.null.php

    The special NULL value represents a variable with no value. NULL is the only possible value of type null.

    You can easily test by performing a var_dump() on the property and you will see both instances it will be NULL

    class Blah1
    {
        private $foo;
    
        function test()
        {
            var_dump($this->foo);
        }
    }
    
    $test1 = new Blah1();
    $test1->test(); // Outputs NULL
    
    
    class Blah2
    {
        private $foo = NULL;
    
        function test()
        {
            var_dump($this->foo);
        }
    }
    
    $test2 = new Blah2();
    $test2->test(); // Outputs NULL
    

    Typed properties

    PHP 7.4 adds typed properties which do not default to null by default like untyped properties, but instead default to a special "uninitialised" state which will cause an error if the property is read before it is written. See the "Type declarations" section on the PHP docs for properties.

提交回复
热议问题