代码如下,因为构造函数中需要传入多个值,而每次传入的值个数可能不固定,如果没有传入,就使用构造甘薯中默认的值,所以这里我采用数组传入,在下面我已经通过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,1212
port:80
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,1212
port:80
$str 就一个变量啊,程序怎么会自动理解为两个呢
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
<?php
class 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
$obj = $ref->newInstanceArgs($data);