Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use variable name to call a class?

Tags:

php

laravel

I want to use a variable (string value) to call a Class. Can I do it ? I search for PHP ReflectionClass but I do not know how to use a 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();
        }
    }
like image 701
Kieu Duy Avatar asked Feb 07 '23 21:02

Kieu Duy


2 Answers

Without ReflectionClass:

$instance = new $className();

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

$instance = (new \ReflectionClass($className))->newInstance();
like image 112
SOFe Avatar answered Feb 10 '23 09:02

SOFe


I found one like this

$str = "ClassName";
$class = $str;
$object = new $class();
like image 44
magic-sudo Avatar answered Feb 10 '23 11:02

magic-sudo