Maher4Ever
Maher4Ever

Reputation: 1280

How to initialize objects with unknown arguments?

I'm trying to make a class which has methods called using PHP's __call() magic method. This magic method will then be initializing another object like this :

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 that code is totally worng! I'm just trying to make clear what I want to do.

I want to be able to pass the $arguments when initializing a new object, one after the other, So that each child class could define it's necessary arguments.

I figured a solution using eval() , but I really don't like it.

Any Ideas ?

Upvotes: 3

Views: 194

Answers (1)

zerkms
zerkms

Reputation: 254926

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

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

Upvotes: 3

Related Questions