ReflectionClass::newInstance

(PHP 5, PHP 7, PHP 8)

ReflectionClass::newInstanceBelirtilen değiştirgelerden yeni bir sınıf örneği oluşturur

Açıklama

public ReflectionClass::newInstance(mixed $değiştirgeler): object

Belirtilen değiştirgelerden yeni bir sınıf örneği oluşturur. Belirtilen değiştirgeler sınıf kurucusuna aktarılır.

Değiştirgeler

değiştirgeler

call_user_func() işlevindeki gibi işleve istenen sayıda değiştirge aktarılabilir.

Dönen Değerler

Hatalar/İstisnalar

Sınıfın kurucusu public değilse bir ReflectionException yavrulanır.

Sınıfın bir kurucusu yoksa ve değiştirgeler bir veya daha fazla değiştirge içeriyorsa bir ReflectionException yavrulanır.

Ayrıca Bakınız

add a note add a note

User Contributed Notes 2 notes

up
0
feryardiant at pm dot me
2 years ago
I don't know why it's not documented anywhere, when you (accidentally) pass an abstract class name you'll get the instance of Error class instead of ReflectionException class.

<?php
function reflect(string $class) {
    try {
        (new
ReflectionClass($class))->newInstance();
    } catch (
Throwable $e) {
        echo
get_class($e) . ' : ' . $e->getMessage() . PHP_EOL;
    }
}

abstract class
A {}

class
B {
    private function
__construct() {}
}

reflect(A::class); // => Error : Cannot instantiate abstract class A
reflect(B::class); // => ReflectionException : Access to non-public constructor of class B
up
-5
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