首页 > PHP Class 属性赋值 NULL 与 不赋值的区别

PHP Class 属性赋值 NULL 与 不赋值的区别

PHP 定义 Class 属性时,赋值NULL与不赋值有什么区别呢?
比如:
代码1:

class Base
{
    protected $_db = NULL;
   
    function __construct()
    {
    
    }
}

代码2:

class Base
{
    protected $_db;
   
    function __construct()
    {
    
    }
}

以上代码有什么区别呢?


声明变量赋初值是个好习惯


class Base
{
    protected $_db = NULL;
   
    function __construct()
    {
    
    }
}

$b=new Base();

var_dump($b);
输出:object(Base)#1 (1) { ["_db":protected]=> NULL }


class Base
{
    protected $_db;
   
    function __construct()
    {
    
    }
}

$b=new Base();

var_dump($b);
也输出:object(Base)#1 (1) { ["_db":protected]=> NULL }

但当你不是在类中,直接定义一个变量

$var;

$var_dump($var) 时,回抛出一个Notice: Undefined variable:的警告,但是还是输出null

没区别

http://php.net/manual/zh/language.types.null.php

【热门文章】
【热门文章】