首页 > 解决方案 > PHP - 创建类的实例(数组参数)

问题描述

现在,我正在创建一个这样的实例:

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

    // Do other stuff before

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

    // Do other stuff before

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

问题是:

将数组用作单个参数,将其解释为参数数组而不是单个参数。我还考虑过使用“func_get_args”或添加第三个可选参数,该参数定义是否有一个数组作为参数或给定的数组是否包含所有参数,但我不喜欢这样。

例如:

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

// should interpreted as:

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

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

function __construct($myArray) {}

有人有想法吗?

标签: phpreflectioninstance

解决方案


我会使用可变长度参数来处理这个:

function newInstance($clazz, ...$parameters) {
    // Do other stuff before

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

newInstance('clazzname', 'my', 'array');
// new clazzname('my', 'array');

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

推荐阅读