Home >Backend Development >PHP Tutorial >PHP Class 属性赋值 NULL 与 不赋值的区别

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

WBOY
WBOYOriginal
2016-06-06 20:11:071173browse

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

<code>class Base
{
    protected $_db = NULL;
   
    function __construct()
    {
    
    }
}
</code>

代码2:

<code>class Base
{
    protected $_db;
   
    function __construct()
    {
    
    }
}</code>

以上代码有什么区别呢?

回复内容:

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

<code>class Base
{
    protected $_db = NULL;
   
    function __construct()
    {
    
    }
}
</code>

代码2:

<code>class Base
{
    protected $_db;
   
    function __construct()
    {
    
    }
}</code>

以上代码有什么区别呢?

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

没区别

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

<code>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</code>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn