如何手动调用类构造函数

如何手动调用类构造函数

本文介绍了PHP [OOP] - 如何手动调用类构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参阅下面的代码:

  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.}

现在,问题是在第09行调用

$ <$ p




有可能吗?如果那么如何?

解决方案

这是不可能防止构造函数被调用时的对象构造(代码中的第9行)。如果在你的 __ construct()方法中发生了一些你希望推迟到构造之后的函数,你应该把它移动到另一个方法。该方法的好名字可能是 init()



为什么不这样做?

  class Test {
public function __construct($ param1,$ param2,$ param3){
echo $ param1 $ param2。$ param3;
}
}

$ ob = new Test('p1','p2','p3');

编辑:我只是想一个hacky方式,你可以防止构造函数被调用。您可以子类 Test ,并用一个空的无用的构造函数覆盖构造函数。

  class SubTest extends Test {
public function __construct(){
//不调用parent :: __ construct()
}

public function init($ param1,$ param2,$ param3){
parent :: __ construct($ param1,$ param2,$ param3);
}
}

$ ob = new SubTest();
$ ob-> init('p1','p2','p3');

这可能是有意义的,如果你处理一些代码,需要解决编写不良的构造函数的一些恼人的行为。


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?

解决方案

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.

这篇关于PHP [OOP] - 如何手动调用类构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 18:08