我想使用变量(字符串值)来调用Class。我能做到吗?我搜索PHP ReflectionClass,但我不知道如何使用Reflection Result中的方法。喜欢这个:
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();
使用 ReflectionClass:使用 ReflectionClass::newInstance()
方法:
$instance = (new 'ReflectionClass($className))->newInstance();
我找到了这样的一个
$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;
使用尝试/捕获与重新抛出
一个不错的方法是尝试并抓住它是否出错。
$className = 'Foo';
try {
$foo = new $className;
}
catch (Exception $e) {
throw new MyClassNotFoundException($e);
}
$foo->bar();