How to pass a value to the constructor 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 used "," connected, why after passing in & nbsp; all are transferred to the $ host variable. The result is & nbsp; ho how to pass the value to the constructor in the class in the form of a variable
The code is as follows, because the constructor needs to input multiple values, and the number of incoming values may not be fixed each time. if not, the default value in sweet potato is constructed, so here I use arrays for input. below I have used implode to cut the array into strings and used "," connected. why are the strings transferred to the $ host variable? 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'] = '123 ';
$ Str = implode (',', $ data );
$ Obj = new test ($ str );


Result:

Host: 192.168.1.1 and 1212
Port: 80
Share:
------ Solution --------------------
$ 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.