How to Pass values to constructors in the class in the form of variables

Source: Internet
Author: User
How to pass the value code to the constructor in the form of variables is as follows, because the constructor needs to input multiple values, and the number of values imported each time may not be fixed. if not, the default value in the construction of sweet potato is used, so here I use an array to pass in. below I have used implode to cut the array into strings and connected it, why are the $ host variables transferred in? the result is:
Host: 192.168.1.1 and 1212
Port: 80

That is to say, the post is passed to $ host, and the port is used by default in the class.
class test{public function __construct($host="127.0.0.1",$port="80"){echo 'host:'.$host."
";echo 'port:'.$port;}}$data['host']='192.168.1.1';$data['port']='1212';$str=implode(',',$data);$obj=new test($str);


Result:
host:192.168.1.1,1212port:80


Reply to discussion (solution)

Low-level errors
$ Str is just a variable. how can a program automatically understand it as two?

So you passed a host variable 192.168.1.1. if the 1212 port variable is not passed, the default 80

Write like this

class test{    public function __construct($host="127.0.0.1",$port="80")    {        echo 'host:'.$host."
"; 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

 ";        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 );

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.