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();
}
}
Without ReflectionClass:
$instance = new $className();
With ReflectionClass: use the ReflectionClass::newInstance()
method:
$instance = (new \ReflectionClass($className))->newInstance();
I found one like this
$str = "ClassName";
$class = $str;
$object = new $class();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With