Heim  >  Artikel  >  Backend-Entwicklung  >  函数参数NULL有关问题

函数参数NULL有关问题

WBOY
WBOYOriginal
2016-06-13 11:59:031200Durchsuche

函数参数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 />

------解决方案--------------------
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() {}
------解决方案--------------------
但是面向对象编程,重载是一个很重要的概念(方法)

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