My problem is to construct dynamically the call of constructors with the right number of parameters.
PHP7
I created a function createObjectFromJson
which create an instance of object from a json file. The object classes already exist, and constructor methods can receive 0 or many parameters.
I have an array with the list of json properties to pass to constructor of the object.
My problem is to construct dynamically the call of the constructor with the right number of parameters.
<?
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;
}
}?>
With this code I have the following error :
Uncaught ArgumentCountError: Too few arguments to function Foo::__construct().
I understand I’m passing 1 argument ( one array) instead of 2 arguments expected. How convert an array to a correct arguments strings?