0

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?

Zeshan
  • 2,496
  • 3
  • 21
  • 26
Franck
  • 1
  • 1
    Possible duplicate of [Passing an Array as Arguments, not an Array, in PHP](https://stackoverflow.com/questions/744145/passing-an-array-as-arguments-not-an-array-in-php) – HTMHell Aug 06 '19 at 07:29

1 Answers1

0

Use reflection:

$refClz = new ReflectionClass($class);
$objectReturn = $refClz->newInstanceArgs($arg); 
shingo
  • 18,436
  • 5
  • 23
  • 42