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!
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 (__)!
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.
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();
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.
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 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With