Reputation: 439
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
Reputation: 5806
The risk is that the class doesn't exist. So it's better to check before instantiating.
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;
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
Reputation: 5108
You can use directly like below
$class = new $key();
$data[strtolower($key) . '._items'] = $class->get();
Upvotes: 2
Reputation: 1266
I found one like this
$str = "ClassName";
$class = $str;
$object = new $class();
Upvotes: 2
Reputation: 8224
Without ReflectionClass:
$instance = new $className();
With ReflectionClass: use the ReflectionClass::newInstance()
method:
$instance = (new \ReflectionClass($className))->newInstance();
Upvotes: 3