Pass variable number of variables to a class in PHP

前端 未结 7 1846
别跟我提以往
别跟我提以往 2021-02-14 14:12

I need to pass a variable number of strings to instantiate different classes. I can always do a switch on the size of the array:

switch(count($a)) {
case 1:
            


        
7条回答
  •  半阙折子戏
    2021-02-14 14:51

    It seems that reflection can pull this one out of the hat for you. This comes to you courtesy of the PHP call_user_func_array notes. The following code will create a class by calling the constructor with the contents of your array.

    newInstanceArgs($args);
    // this is the same as: new myCommand('a', 'b');
    
    ?>
    

提交回复
热议问题