因此我能否安全地重构所有实例
class Blah
{
// ...
private $foo = null;
// ...
}
到
class Blah
{
// ...
private $foo;
// ...
}
?
最佳答案
无类型属性
简单的回答,是的。见 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.
您可以通过对属性执行 var_dump()
轻松进行测试,您将看到两个实例都是 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
类型化属性
PHP 7.4 添加了类型化属性,默认情况下它不像非类型化属性那样默认为 null
,而是默认为特殊的“未初始化”状态,如果在属性被读取之前会导致错误书面。请参阅 PHP docs for properties 上的“类型声明”部分.
关于php - 属性默认值为 null 是否与无默认值相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14097258/