How to use a variable name to call a class?

I want to use a variable (string value) to call a class. Can I do it? I am looking for PHP ReflectionClass, but I do not know how to use the method from Reflection Result. Like this:

    foreach($menuTypes as $key => $type){
        if($key != 'Link'){
            $class = new \ReflectionClass('\App\Models\\' . $key);

            //Now $class is a ReflectionClass Object
            //Example: $key now is "Product"
            //I'm fail here and cannot call the method get() of 
            //the class Product

            $data[strtolower($key) . '._items'] = $class->get();
        }
    }
+4
source share
4 answers

Without ReflectionClass:

$instance = new $className();

With ReflectionClass: use the method ReflectionClass::newInstance():

$instance = (new \ReflectionClass($className))->newInstance();
+3
source

I found one such

$str = "ClassName";
$class = $str;
$object = new $class();
+3
source

,

$class = new $key();

$data[strtolower($key) . '._items'] = $class->get();
+2

, . .

php class_exists

Php .

$className = 'Foo';
if (!class_exists($className)) {
    throw new Exception('Class does not exist');
}

$foo = new $className;

try/catch rethrow

, .

$className = 'Foo';

try {
    $foo = new $className;
}
catch (Exception $e) {
    throw new MyClassNotFoundException($e);
}

$foo->bar();
0

Source: https://habr.com/ru/post/1626326/


All Articles