0

I have a piece of code that basically creates an instance of a class on-the-fly:

$class = 'user';
return new $class;

The challenge is that I have the constructor's arguments in an array format and they're obviously different from class to class -- so there is no pattern at all that I can make anything on top of that. There are some workarounds here to extract these arguments from the array and pass it all through in a way like this:

$args = array( 'one', 'two' );
// some code to generate $arg1, $arg2, etc.
return new $class( $arg1, $arg2 );

However, I really prefer to do it in a smarter way. As far as I can see there is no way to make use of call_user_func and call_user_func_array unless I forget about the constructor and initialize it after instantiation.

Update

Basically I'm looking for something like this:

return magic_func( 'className', array('one', 'two') );

2 Answers 2

6
return (new ReflectionClass($class))->newInstanceArgs($args);

See http://php.net/manual/en/reflectionclass.newinstanceargs.php

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! for some reason I got a syntax error unexpected T_OBJECT_OPERATOR, however when I did break it down into two statements -- like in the manual, then it worked out as expected!
3

A newer syntax, using variable-length argument lists:

return new $class(...$args);

Comments

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.