Pass variable number of variables to a class in PHP

前端 未结 7 1685
别跟我提以往
别跟我提以往 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:29

    // Constructs an instance of a class with a variable number of parameters.
    
    function make() { // Params: classname, list of constructor params
     $args = func_get_args();
     $classname = array_shift($args);
     $reflection = new ReflectionClass($classname);
     return $reflection->newInstanceArgs($args);
    }
    

    How to use:

    $MyClass = make('MyClass', $string1, $string2, $string3);
    

    Edit: if you want to use this function with your $a = array("variable1", "variable2", 'variable3", ...)

    call_user_func_array('make', array_merge(array('MyClass'), $a));
    

提交回复
热议问题