【发布时间】:2019-08-06 07:26:45
【问题描述】:
我的问题是使用正确数量的参数动态构造构造函数的调用。
PHP7
我创建了一个函数createObjectFromJson,它从一个json文件创建一个对象实例。对象类已经存在,构造方法可以接收0个或多个参数。
我有一个包含 json 属性列表的数组,要传递给对象的构造函数。
我的问题是使用正确数量的参数动态构造构造函数的调用。
<?
trait jsonHelper {
static function jsonToObject(string $json) {
$constructArgument = ["foo"=>["p1","p2"]];
$class = __CLASS__;
$jsonArray = json_decode($json, true);
// construit les arguments à passer au constructeur
$arg;
if(isset($constructArgument[$class])) {
$arg = [];
foreach($constructArgument[$class] as indice=>$constructArgument)
$constructArgumentValue;
if(isset($jsonArray[$constructArgument])){
$constructArgumentValue = $jsonArray[$constructArgument];
}
array_push($arg, $jsonArray[$constructArgument]);
}
}
$objectReturn = new $class($arg);
foreach($objectReturn as $key=>$value){
// initialize each properties
....
}
}
}
class Foo {
Use jsonHelper;
public $p1;
public $p2;
function __construct($p1, $p2){
$this->p1 = $p1;
$this->p2 = $p2;
}
}?>
使用此代码我有以下错误:
未捕获的 ArgumentCountError:参数太少而无法运行 Foo::__construct()。
我知道我传递的是 1 个参数(一个数组)而不是预期的 2 个参数。如何将数组转换为正确的参数字符串?
【问题讨论】:
标签: php