函数参数NULL有关问题

WBOY
Release: 2016-06-13 11:59:03
Original
1198 people have browsed it

函数参数NULL问题
一个数据连接初始化的代码,本人之前学C#的,就是构造函数里的$dbo=NULL这个看不懂,请指教。
我可不可以不要=NULL呢,直接用$dbo,我个人理解是$dbo=NULL这条语句就表示$dbo不是object类型了,那它下面为什么还要去判断? $dbo=NULL这个NULL值不会带到函数里面去吗?
protected function __construct($dbo)
{
      //...
}

<br /><br />	class DB_Connect{<br />		<br />		protected $db;<br />		<br />		protected function __construct($dbo=NULL)<br />		{<br />			if(is_object($dbo))<br />			{<br />				$this->db=$dbo;				<br />			}<br />			else<br />			{<br />				$dsn="mysql:host=".DB_HOST."; dbname=".DB_NAME;<br />				try <br />				{<br />					$this->db=new PDO($dsn,DB_USER,DB_PASS);<br />				}<br />				catch(Exception $e)<br />				{<br />					die($e->getMessage());<br />				}<br />			}<br />		}		<br />	<br />	}	<br />
Copy after login

------解决方案--------------------
function __construct($dbo=NULL)
表示 $dbo 这个参数是可缺省的,因为他有初值 NULL
如果仅是
function __construct($dbo)
那么 $dbo 这个参数就一定要传入的

由于是可缺省参数,所以
new DB_Connect();
new DB_Connect($db);
都不会出错


C# 支持重载,所以对于这种情况你可能是这样写
DB_Connect::__construct($dbo) {}
DB_Connect::__construct() {}
------解决方案--------------------
但是面向对象编程,重载是一个很重要的概念(方法)

Related labels:
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!