略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: ReflectionClass::newInstance

2024-11-13

ReflectionClass::newInstance

(PHP 5, PHP 7, PHP 8)

ReflectionClass::newInstance从指定的参数创建一个新的类实例

说明

public ReflectionClass::newInstance(mixed $args, mixed $... = ?): object

创建类的新的实例。给出的参数将会传递到类的构造函数。

参数

args

接受可变数目的参数,用于传递到类的构造函数,和 call_user_func() 很相似。

返回值

错误/异常

如果类的构造函数不是 public 的将会导致一个 ReflectionException

args 指定了一个或多个参数,而类不具有构造函数时,将导致一个 ReflectionException

参见

add a noteadd a note

User Contributed Notes 1 note

up
-5
glen at delfi dot ee
6 years ago
looks like reflection class newInstance creates in memory representation of code where values are used, so using reference as constructor signature, you can not use this method.

as  the same input if called via new, or new $class works, but not via reflection:

class a {
     public function __construct(&$a, $c) {
     }
}

// this works
$A = new stdClass();
$a = new a($A, 11);

// also this works
$classname = "a";
$a = new $classname($A, 10);

// but this fails:
$r = new ReflectionClass("a");
$r->newInstance($A, 10);

PHP Warning:  Parameter 1 to a::__construct() expected to be a reference, value given in reflection.php on line 15

PHP Warning:  ReflectionClass::newInstance(): Invocation of a's constructor failed in reflection.php on line 15

官方地址:https://www.php.net/manual/en/reflectionclass.newinstance.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3