3

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();
        }
    }
Kieu Duy
  • 429
  • 1
  • 4
  • 12

4 Answers4

3

Without ReflectionClass:

$instance = new $className();

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

$instance = (new \ReflectionClass($className))->newInstance();
SOFe
  • 7,867
  • 4
  • 33
  • 61
2

I found one like this

$str = "ClassName";
$class = $str;
$object = new $class();
magic-sudo
  • 1,206
  • 9
  • 15
2

You can use directly like below

$class = new $key();

$data[strtolower($key) . '._items'] = $class->get();
Edwin Alex
  • 5,118
  • 4
  • 28
  • 50
0

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();
schellingerht
  • 5,726
  • 2
  • 28
  • 56