Home >Backend Development >PHP Tutorial > 怎么通过变量的形式向类中的构造函数传值

怎么通过变量的形式向类中的构造函数传值

WBOY
WBOYOriginal
2016-06-13 12:41:31874browse

如何通过变量的形式向类中的构造函数传值
代码如下,因为构造函数中需要传入多个值,而每次传入的值个数可能不固定,如果没有传入,就使用构造甘薯中默认的值,所以这里我采用数组传入,在下面我已经通过implode将数组切成字符串并用","连接了,为什么传进去后 都转入了$host的变量下,结果是 
host:192.168.1.1,1212  
port:80

也就是说post传到了$host里而port还是用的类中默认的

<br />
class test{<br />
	public function __construct($host="127.0.0.1",$port="80")<br />
	{<br />
		echo 'host:'.$host."<br>";<br />
		echo 'port:'.$port;<br />
	}<br />
<br />
}<br />
<br />
$data['host']='192.168.1.1';<br />
$data['port']='1212';<br />
$str=implode(',',$data);<br />
$obj=new test($str);<br />


结果:
<br />
host:192.168.1.1,1212<br />
port:80<br />

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