Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP[OOP] - How to call class constructor manually?

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?

like image 653
A.N.M. Saiful Islam Avatar asked Dec 14 '09 06:12

A.N.M. Saiful Islam


People also ask

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 do you call a class constructor in PHP?

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.

Can we call constructor manually?

You can call a constructor manually with placement new.

How do you call a class constructor?

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.


1 Answers

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.

like image 78
Asaph Avatar answered Oct 22 '22 19:10

Asaph