Search code examples
phpoopdynamic-data

Dynamically call Class with variable number of parameters in the constructor


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-array.php . What I want to do is nearly identical, but instead of a function, I want to call a PHP class with a variable number of parameters in it's constructor.

It would work something like the below, but I won't know the number of parameters, so I won't know how to instantiate the class.

<?php
//The class name will be pulled dynamically from another source
$myClass = '\Some\Dynamically\Generated\Class';
//The parameters will also be pulled from another source, for simplicity I
//have used two parameters. There could be 0, 1, 2, N, ... parameters
$myParameters = array ('dynamicparam1', 'dynamicparam2');
//The instantiated class needs to be called with 0, 1, 2, N, ... parameters
//not just two parameters.
$myClassInstance = new $myClass($myParameters[0], $myParameters[1]);

Solution

  • 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);