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

WBOY
Release: 2016-06-06 20:11:07
Original
1128 people have browsed it

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

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

代码2:

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

以上代码有什么区别呢?

回复内容:

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

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

代码2:

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

以上代码有什么区别呢?

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

没区别

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>
Copy after login
Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!