3

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 ?

1 Answer 1

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

class a
{
    public function __construct($b, $c, $d)
    {
        var_dump($b, $c, $d);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, that was it. Thank you so much ^^

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.