如何检查是否可以使用PHP实例化对象

时间:2012-08-30 19:50:47

标签: php object instantiation

我不能这样做,但想知道什么会起作用:

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
}

4 个答案:

答案 0 :(得分:7)

您可以使用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!
    }
}

答案 1 :(得分:2)

请参阅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
}

答案 2 :(得分:0)

答案 3 :(得分:0)

您可以使用class_exists函数查看某个类是否存在。

请参阅手册中的更多内容:class_exists