Php 如何使用变量名调用类?

Php 如何使用变量名调用类?,php,laravel,Php,Laravel,我想使用一个变量(字符串值)来调用一个类。我能做吗?我搜索PHP ReflectionClass,但不知道如何使用反射结果中的方法。像这样: foreach($menuTypes as $key => $type){ if($key != 'Link'){ $class = new \ReflectionClass('\App\Models\\' . $key); //Now $class is a Reflecti

我想使用一个变量(字符串值)来调用一个类。我能做吗?我搜索PHP ReflectionClass,但不知道如何使用反射结果中的方法。像这样:

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

没有ReflectionClass:

$instance = new $className();
使用ReflectionClass:使用:

我找到一个像这样的

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

您可以像下面这样直接使用

$class = new $key();

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

风险在于该类不存在。因此,最好在实例化之前进行检查

使用php的class_exists方法 Php有一个内置的方法来检查类是否存在

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

$foo = new $className;
用try/catch和rethrow 一个很好的方法是在出错时尝试和捕捉

$className = 'Foo';

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

$foo->bar();

你说叫一个班是什么意思?是否要创建类实例?@IhorBurlachenko create instalce(调用类构造函数)看起来不需要反射。如果要实例化对象,可以执行
$object=new$key()@jeroen&Ihor Burlachenko:这正是我想要的。很简单,谢谢!是的可能重复,您可以使用try/catch。尝试实例化>类不存在>异常>未找到类
$className = 'Foo';

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

$foo->bar();