Creating an instance of a dynamic class programmatically in PHP with variable arguments?

I have code that creates an instance of an ad with a dynamic class (i.e. from a variable):

$instance = new $myClass(); 

Since the constructor has different arguments, depending on the value of $myClass , how do I pass a variable argument list to a new statement? Is it possible?

+7
source share
3 answers
 class Horse { public function __construct( $a, $b, $c ) { echo $a; echo $b; echo $c; } } $myClass = "Horse"; $refl = new ReflectionClass($myClass); $instance = $refl->newInstanceArgs( array( "first", "second", "third" )); //"firstsecondthird" is echoed 

You can also check the constructor in the above code:

 $constructorRefl = $refl->getMethod( "__construct"); print_r( $constructorRefl->getParameters() ); /* Array ( [0] => ReflectionParameter Object ( [name] => a ) [1] => ReflectionParameter Object ( [name] => b ) [2] => ReflectionParameter Object ( [name] => c ) ) */ 
+10
source

The easiest way is to use an array.

 public function __construct($args = array()) { foreach($array as $k => $v) { if(property_exists('myClass', $k)) // where myClass is your class name. { $this->{$k} = $v; } } } 
+1
source

I don’t know why, but I don’t like using the new operator in my code.

Here is a static function to instantiate a class called statically.

 class ClassName { public static function init(){ return (new ReflectionClass(get_called_class()))->newInstanceArgs(func_get_args()); } public static function initArray($array=[]){ return (new ReflectionClass(get_called_class()))->newInstanceArgs($array); } public function __construct($arg1, $arg2, $arg3){ ///construction code } } 

If you use it inside a namespace, you need to avoid the ReflectionClass as follows: new \ ReflectionClass ...

Now you can call the init () method with a variable number of arguments and pass it to the constructor and return the object for you.

The usual way using the new

 $obj = new ClassName('arg1', 'arg2', 'arg3'); echo $obj->method1()->method2(); 

Built-in method using the new

 echo (new ClassName('arg1', 'arg2', 'arg3'))->method1()->method2(); 

Static call using init instead of new

 echo ClassName::init('arg1', 'arg2', 'arg3')->method1()->method2(); 

Static call using initArray instead of new

 echo ClassName::initArray(['arg1', 'arg2', 'arg3'])->method1()->method2(); 

The good thing about static methods is that you can run some pre-build operations in init methods, such as checking constructor arguments.

0
source

All Articles