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

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

WBOY
WBOYOriginal
2016-06-23 14:17:191131browse

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

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

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


结果:
host:192.168.1.1,1212port:80


回复讨论(解决方案)

低级错误
$str 就一个变量啊,程序怎么会自动理解为两个呢

这么传参等于是你传了一个host变量192.168.1.1,1212 port变量没传 还是使用类默认的80

要这样写

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

<?phpclass test{	public static function new_object($data = array()) {		switch(count($data)) {			case 2:				return new self($data['host'], $data['port']);			case 1:				return new self($data['host']);			default:				return new self();		}	}    public function __construct($host="127.0.0.1",$port="80")    {        echo 'host:'.$host."<br>";        echo 'port:'.$port;    } } $data['host']='192.168.1.1';$data['port']='1212';//$str=implode(',',$data);//$obj=new test($str);$obj = test::new_object($data);


host:192.168.1.1
port:1212

$ref = new ReflectionClass('test');
$obj = $ref->newInstanceArgs($data);

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