Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 989
Maher4Ever Avatar asked Dec 16 '25 16:12

Maher4Ever


1 Answers

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

class a
{
    public function __construct($b, $c, $d)
    {
        var_dump($b, $c, $d);
    }
}
like image 143
zerkms Avatar answered Dec 19 '25 04:12

zerkms



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!