samedi 7 juillet 2018

PHP - Create instance of class (array param)

For now, I'm creating an instance like this:

function newInstance($clazz, $parameters = []) {

    // Do other stuff before

    if(!is_array($parameters)) {
        $parameters = [$parameters];
    }

    // Do other stuff before

    return (new ReflectionClass($clazz))->newInstanceArgs($parameters)
}

The problem is:

Using an array as a single parameter, interprets it as an array of parameters instead of a single one. I also thought about using "func_get_args" or adding a third optional parameter which defines if there's an array as parameter or the given array contains all parameters, but I don't like that.

For example:

newInstance('clazzname', ['my', 'array']);

// should interpreted as:

function __construct($firstString, $secondString$) {}

// and sometimes as (depends on the class):

function __construct($myArray) {}

Anyone have an idea?





Aucun commentaire:

Enregistrer un commentaire