CakeFest 2024: The Official CakePHP Conference

ReflectionClass::newInstance

(PHP 5, PHP 7, PHP 8)

ReflectionClass::newInstance指定した引数でクラスの新しいインスタンスを作成する

説明

public ReflectionClass::newInstance(mixed ...$args): object

クラスの新しいインスタンスを作成します。指定した引数をクラスのコンストラクタに渡します。

パラメータ

args

可変長の引数を受け付け、それを call_user_func() と同じ方式でクラスのコンストラクタに渡します。

戻り値

エラー / 例外

コンストラクタが public でない場合は ReflectionException が発生します。

クラスにコンストラクタがないときに args を指定すると ReflectionException が発生します。

参考

add a note

User Contributed Notes 1 note

up
-11
glen at delfi dot ee
8 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
To Top