Is a property default value of null the same as no

2020-04-01 09:43发布

And can I therefore safely refactor all instances of

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

to

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

?

2条回答
做自己的国王
2楼-- · 2020-04-01 10:07

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
查看更多
冷血范
3楼-- · 2020-04-01 10:19

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.

查看更多
登录 后发表回答