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

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

    Note that if the constructor (__construct method) contains arguments passed by reference, then the function:

    call_user_func_array
    

    will fail with an error.

    I suggest you to use Reflection class instead; here is how you can do so:

    // assuming that class file is already included.
    
    $refMethod = new ReflectionMethod('class_name_here',  '__construct');
    $params = $refMethod->getParameters();
    
    $re_args = array();
    
    foreach($params as $key => $param)
    {
        if ($param->isPassedByReference())
        {
            $re_args[$key] = &$args[$key];
        }
        else
        {
            $re_args[$key] = $args[$key];
        }
    }
    
    $refClass = new ReflectionClass('class_name_here');
    $class_instance = $refClass->newInstanceArgs((array) $re_args);
    

提交回复
热议问题