2012-08-30 51 views
4

我不能做到这一点,但不知道什么工作进行实例化:如何检查是否一个对象可以使用PHP

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 
} 

回答

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 
} 
0

可以使用class_exists功能,看是否有阶级存在与否。

查看更多手册:class_exists

6

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

即使其他的答案提供_sufficient_的解决方案,这应该成为进一步迈出关键一步的公认答案 – Ejaz

相关问题