Dynamically call Class with variable number of parameters in the constructor

后端 未结 4 1186
广开言路
广开言路 2020-12-09 10:35

I know that it is possible to call a function with a variable number of parameters with call_user_func_array() found here -> http://php.net/manual/en/function.call-user-func

4条回答
  •  爱一瞬间的悲伤
    2020-12-09 10:59

    You can do the following using ReflectionClass

    $myClass = '\Some\Dynamically\Generated\a';
    $myParameters = array ('dynamicparam1', 'dynamicparam2');
    
    $reflection = new \ReflectionClass($myClass); 
    $myClassInstance = $reflection->newInstanceArgs($myParameters); 
    

    PHP manual: http://www.php.net/manual/en/reflectionclass.newinstanceargs.php

    Edit:

    In php 5.6 you can achieve this with Argument unpacking.

    $myClass = '\Some\Dynamically\Generated\a';
    $myParameters = ['dynamicparam1', 'dynamicparam2'];
    
    $myClassInstance = new $myClass(...$myParameters); 
    

提交回复
热议问题