How to initialize objects with unknown arguments?

I am trying to create a class that has methods called using the PHP __call()magic method. Then this magic method will initialize another object as follows:

public function  __call($function, $arguments) {

    /* Only allow function beginning with 'add' */
    if ( ! preg_match('/^add/', $function) ) {
        trigger_error('Call to undefined method ' . __CLASS__ . '::' . $function, E_USER_ERROR);
    }

    $class = 'NamodgField_' . substr($function, 3); /* Ex: $function = addTextField() => $class = NamodgField_TextField */

    /* This doesn't work! Because $class is not an object yet */
    call_user_func_array( array(new $class, '__construct'), $arguments);
}

The last line of this code is completely erased! I'm just trying to figure out what I want to do.

I want to be able to pass $argumentsone after another when initializing a new object so that each child class can determine the necessary arguments.

I solved the solution with help eval(), but I really don't like it.

Any ideas?

+3
source share
1 answer
$class = new ReflectionClass('a');
$object = $class->newInstanceArgs(array(1, 2, 3));

class a
{
    public function __construct($b, $c, $d)
    {
        var_dump($b, $c, $d);
    }
}
+3
source

Source: https://habr.com/ru/post/1785807/


All Articles