1

The title is really explicit, but I am going to give an example:

class Foo
{
    public function __construct($param1, $param2) {
        echo 'Class name: ' . __CLASS__ . "\n" .
             'param1 = ' . $param1 . "\n" .
             'param2 = ' . $param2;
    }
}

$class_name = 'Foo';
$params =
    [
    'content1',
    'content2'
    ];

Having this code, how can I create an instance of Foo, using the parameters in $params.

I know I can do

$class = new $class_name($params);

But this would pass the parameters as one array, I would like it to expand the parameters. The following would be the behavior I would like:

$class = new $class_name($param[0], $param[1]);

Thank you!

1
  • Other than the answer posted, anything else would be a hack. You either want 2 args or you want an array of args. Commented Mar 18, 2015 at 21:11

2 Answers 2

1

If you have 5.6:

$instance = new $class(...$args);

If not use reflection:

$reflect  = new ReflectionClass($class);
$instance = $reflect->newInstanceArgs($args);
Sign up to request clarification or add additional context in comments.

Comments

0

I hesitate to post this because really you should design to either accept an array of parameters or individual parameters. However, here are to hackish ways:

Using another function:

public function init($params) {
    echo 'Class name: ' . __CLASS__ . "\n" .
         'param1 = ' . $params[0] . "\n" .
         'param2 = ' . $params[1];
}

public function __construct($param1, $param2=null) {
    if(!is_array($param1)) {
        $param1 = func_get_args();
    }
    call_user_func_array(array($this, 'init'), $param1);
}

Doing it all in the __construct:

public function __construct($param1, $param2=null) {
    if(!is_array($param1)) {
        $param1 = func_get_args();
    }
    echo 'Class name: ' . __CLASS__ . "\n" .
         'param1 = ' . $param1[0] . "\n" .
         'param2 = ' . $param1[1];
}

1 Comment

Thank you for you answer. My example was only ... an example, I am actually creating a class which executes the specified method in the specified class, and which passes the arguments to this class. This is why I can't modify my receiving class.

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.