我不能这么做,但想知道什么能起作用:
is_object(new Memcache){
//assign memcache object
$memcache = new Memcache;
$memcache->connect('localhost', 11211);
$memcache->get('myVar');
}
else{
//do database query to generate myVar variable
}
您可以使用class_exists()
来检查类是否存在,但如果您可以实例化该类,它将不会返回!
你不能这样做的原因之一可能是它是一个抽象类。要检查它,您应该在之后执行类似的操作,检查class_exists()
。
对于上面的例子来说,这可能是不可能的(有一个抽象类,而不是检查它),但在其他情况下可能会让你头疼:)
//first check if exists,
if (class_exists('Memcache')){
//there is a class. but can we instantiate it?
$class = new ReflectionClass('Memcache')
if( ! $class->isAbstract()){
//dingdingding, we have a winner!
}
}
请参见class_exists
if (class_exists('Memcache')){
//assign memcache object
$memcache = new Memcache;
$memcache->connect('localhost', 11211);
$memcache->get('myVar');
}
else{
//do database query to generate myVar variable
}
查看class_exists()
。
http://php.net/manual/en/function.class-exists.php
您可以使用class_exists
函数查看类是否存在。
请参阅手册中的更多内容:class_exists
ReflectionClass::isInstantiable
方法检查类是否可实例化。
$reflector = new ReflectionClass($concrete);
if ($reflector->isInstantiable()) {
// do something
}