Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a constructor from variable arguments with PHP

I have a function that takes variadic arguments, that I obtain from func_get_args().

This function needs to call a constructor with those arguments. However, I don't know how to do it.

With call_user_func, you can call functions with an array of arguments, but how would you call a constructor from it? I can't just pass the array of arguments to it; it must believe I've called it "normally".

Thank you!

like image 570
zneak Avatar asked Apr 14 '10 18:04

zneak


People also ask

How do you call a constructor in PHP?

A constructor allows you to initialize an object's properties upon creation of the object. If you create a __construct() function, PHP will automatically call this function when you create an object from a class. Notice that the construct function starts with two underscores (__)!

Is it possible to call a constructor manually in PHP?

In PHP you can create objects w/o calling the constructor. But that does not work by using new but by un-serializing an object instance. The constructor can then be called manually.

How can we call a constructor from parent class in PHP?

In order to run a parent constructor, a call to parent::__construct() within the child constructor is required. If the child does not define a constructor then it may be inherited from the parent class just like a normal class method (if it was not declared as private). $obj = new OtherSubClass();

What is parameterized constructor in PHP?

Parameterized Constructor: The constructor of the class accepts arguments or parameters. The -> operator is used to set value for the variables. In the constructor method, you can assign values to the variables during object creation.


1 Answers

For PHP < 5.3 it's not easily doable without first creating an instance of the class with call_user_func_array. However with Reflection this is pretty trivial:

$reflection = new ReflectionClass( 'yourClassName' );
$instance = $reflection->newInstanceArgs( $yourArrayOfConstructorArguments );
like image 161
Decent Dabbler Avatar answered Oct 15 '22 06:10

Decent Dabbler