Kieu Duy
Kieu Duy

Reputation: 439

How to use variable name to call a class?

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();
        }
    }

Upvotes: 3

Views: 2492

Answers (4)

schellingerht
schellingerht

Reputation: 5806

The risk is that the class doesn't exist. So it's better to check before instantiating.

With php's class_exists method

Php has a built-in method to check if the class exists.

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

$foo = new $className;

With try/catch with rethrow

A nice approach is trying and catching if it goes wrong.

$className = 'Foo';

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

$foo->bar();

Upvotes: 0

Edwin Alex
Edwin Alex

Reputation: 5108

You can use directly like below

$class = new $key();

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

Upvotes: 2

magic-sudo
magic-sudo

Reputation: 1266

I found one like this

$str = "ClassName";
$class = $str;
$object = new $class();

Upvotes: 2

SOFe
SOFe

Reputation: 8224

Without ReflectionClass:

$instance = new $className();

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

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

Upvotes: 3

Related Questions