Please see the code bellow:
01. class Test {
02. public function __construct($param1, $param2, $param3) {
03. echo $param1.$param2.$param3;
04. }
05. }
06.
07. $params = array('p1','p2','p3');
08.
09. $ob = new Test;
10.
11. if(method_exists($ob,'__construct')) {
12. call_user_func_array(array($ob,'__construct'),$params);
13. }
Now, the problem is the constructor is called in line 09
But i want to call it manually at line 11-13
Is it possible? If then how? Any idea please?
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.
To call the constructor of the parent class from the constructor of the child class, you use the parent::__construct(arguments) syntax. The syntax for calling the parent constructor is the same as a regular method.
You can call a constructor manually with placement new.
Calling a Constructor You call a constructor when you create a new instance of the class containing the constructor. Here is a Java constructor call example: MyClass myClassVar = new MyClass(); This example invokes (calls) the no-argument constructor for MyClass as defined earlier in this text.
It is not possible to prevent the constructor from being called when the object is constructed (line 9 in your code). If there is some functionality that happens in your __construct()
method that you wish to postpone until after construction, you should move it to another method. A good name for that method might be init()
.
Why not just do this?
class Test {
public function __construct($param1, $param2, $param3) {
echo $param1.$param2.$param3;
}
}
$ob = new Test('p1', 'p2', 'p3');
EDIT: I just thought of a hacky way you could prevent a constructor from being called (sort of). You could subclass Test
and override the constructor with an empty, do-nothing constructor.
class SubTest extends Test {
public function __construct() {
// don't call parent::__construct()
}
public function init($param1, $param2, $param3) {
parent::__construct($param1, $param2, $param3);
}
}
$ob = new SubTest();
$ob->init('p1', 'p2', 'p3');
This is might make sense if you're dealing with some code that you cannot change for some reason and need to work around some annoying behavior of a poorly written constructor.
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