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

≡放荡痞女 提交于 2019-12-19 13:53:04

问题


And can I therefore safely refactor all instances of

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

to

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

?


回答1:


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



回答2:


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

Yes

as per the docs:

The special NULL value represents a variable with no value.

null is a concept of a variable that has not been set to any particular value. It is relatively easy to make mistakes when differentiating between null and empty1 values.

private $foo = null; is exactly equivalent to private $foo;. In both cases the class attribute is defined with a value of null.

isset will correctly return false for both declarations of $foo; isset is the boolean opposite of is_null, and those values are, as per above, null.

For reference, I recommend reviewing the PHP type comparison tables.

1: In this case I am referring to typed values that return true for the empty function, or which are otherwise considered "falsey". I.E. null, 0, false, the empty array (array()), and the empty string (''). '0' is also technically empty, although I find it to be an oddity of PHP as a language.



来源:https://stackoverflow.com/questions/14097258/is-a-property-default-value-of-null-the-same-as-no-default-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!