php - 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) {}
有人有想法吗?
解决方案
我会使用可变长度参数来处理这个:
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']);
推荐阅读
- java - JPA / Hibernate CreationTimestamp 不适用于 PrimaryKeyJoinColumn
- vue.js - 如何将 vue-cli 与同一个项目中现有的不相关 webpack 设置集成?
- node.js - .save() 不会保存模型中的所有内容
- numpy - 使用 numpy.insert 附加 numpy 数组
- ios - 制作椭圆形导航栏
- javascript - 页面加载时自动打开模式
- angular - 在表单组反应形式中插入值
- php - 使用 AJAX 时从页面获取数据消失
- c# - MVC 在两个日期之间从数据库下载数据
- scala - Scala Future 完成后进行清理的最佳实践