And can I therefore safely refactor all instances of
class Blah
{
// ...
private $foo = null;
// ...
}
to
class Blah
{
// ...
private $foo;
// ...
}
?
And can I therefore safely refactor all instances of
class Blah
{
// ...
private $foo = null;
// ...
}
to
class Blah
{
// ...
private $foo;
// ...
}
?
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
Is a property default value of null the same as no default value?
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.