如何检查一个对象是否可以用PHP示例化

lpwwtiir  于 2023-01-19  发布在  PHP
关注(0)|答案(5)|浏览(167)

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

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

vm0i2vca1#

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

zf2sa74q2#

参见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
}
hgc7kmma

hgc7kmma4#

可以使用class_exists函数查看类是否存在。
请参阅手册中的详细信息:class_exists

6xfqseft

6xfqseft5#

ReflectionClass::isInstantiable方法检查类是否可示例化。

$reflector = new ReflectionClass($concrete);

if ($reflector->isInstantiable()) {
    // do something
}

相关问题