属性默认值null是否等于没有默认值? [英] Is a property default value of null the same as no default value?

查看:261
本文介绍了属性默认值null是否等于没有默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我可以安全地重构

And can I therefore safely refactor all instances of

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

to

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

推荐答案

未键入的属性


简单的答案,是的。参见 http://php.net/manual/en/language.types.null .php


特殊的NULL值表示没有值的变量。 NULL是
唯一可能为null类型的值。

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

您可以通过执行 var_dump()上的属性,您将看到两个实例均为 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


类型化属性


PHP 7.4添加了类型化属性默认情况下,如无类型属性一样,默认为 null ,而是默认为特殊的未初始化状态,如果在写入属性之前先读取该属性,则会导致错误。参见类型声明。 有关属性的PHP文档。

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.

这篇关于属性默认值null是否等于没有默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆