Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an object can be instantiated using PHP

I can't do this but wondering what would work:

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
}
like image 738
tim peterson Avatar asked Dec 04 '22 14:12

tim peterson


1 Answers

You can use class_exists() to check if a class exists, but it will not return if you can instantiate that class!

One of the reasons you can't, might be that it is an abstract class. To check for that you should do something like this after you check for class_exists().

This might be impossible (having an abstract class, not checking for it) for above example, but in other situations might be giving you headaches :)

//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!
    }
}
like image 140
Nanne Avatar answered Dec 25 '22 20:12

Nanne