Heim  >  Artikel  >  Backend-Entwicklung  >  PHP Class 属性赋值 NULL 与 不赋值的区别

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

WBOY
WBOYOriginal
2016-06-06 20:11:071128Durchsuche

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>
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn