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

前端 未结 6 498
时光取名叫无心
时光取名叫无心 2020-12-30 07:47

Please see the code bellow:

01. class Test {
02.     public function __construct($param1, $param2, $param3) {
03.         echo $param1.$para         


        
6条回答
  •  误落风尘
    2020-12-30 08:10

    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.

提交回复
热议问题