Pass variable number of variables to a class in PHP

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

    If you must do it this way, you can try:

    $variable1 = 1;
    $variable2 = 2;
    $variable3 = 3;
    $variable4 = 4;
    
    $varNames = array('variable1', 'variable2', 'variable3', 'variable4');
    $reflection = new ReflectionClass('A');
    $myObject = $reflection->newInstanceArgs(compact($varNames)); 
    
    class A
    {
        function A()
        {
            print_r(func_get_args());
        }
    }
    

提交回复
热议问题