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

前端 未结 6 502
时光取名叫无心
时光取名叫无心 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 07:56

    If separating instantiation from initialization isn't strictly a requirement, there are two other possibilities: first, a static factory method.

    class Test {
        public function __construct($param1, $param2, $param3) {
            echo $param1.$param2.$param3;
        }
    
        public static function CreateTest($param1, $param2, $param3) {
            return new Test($param1, $param2, $param3);
        }
    }
    
    $params = array('p1','p2','p3');
    
    if(method_exists($ob,'__construct')) {
        call_user_func_array(array($ob,'CreateTest'),$params);
    }
    

    Or, if you're using php 5.3.0 or higher, you can use a lambda:

    class Test {
        public function __construct($param1, $param2, $param3) {
            echo $param1.$param2.$param3;
        }
    }
    
    $params = array('p1','p2','p3');
    
    $func = function ($arg1, $arg2, $arg3) {
        return new Test($arg1, $arg2, $arg3);
    }
    
    if(method_exists($ob,'__construct')) {
        call_user_func_array($func, $params);
    }
    

    The initialization method described by Asaph is great if for some reason you have a need to logically separate initialization from instantiation, but if supporting your use case above is a special case, not a regular requirement, it can be inconvenient to require users to instantiate and initialize your object in two separate steps.

    The factory method is nice because it gives you a method to call to get an initialized instance. The object is initialized and instantiated in the same operation, though, so if you have a need to separate the two it won't work.

    And lastly, I recommend the lambda if this initialization mechanism is uncommonly used, and you don't want to clutter your class definition with initialization or factory methods that will hardly ever be used.

提交回复
热议问题