It’s really irking me that PHP considers the failure to instantiate an object a Fatal Error (which can’t be caught) for the application as a whole. I have set of classes that aren’t strictly necessary for my application to function–they’re really a convenience. I have a factory object that attempts to instantiate the class variant that’s indicated in a config file.
This mechanism is being deployed for message storage and will support multiple store types:
DatabaseMessageStoreFileMessageStoreMemcachedMessageStore- etc.
A MessageStoreFactory class will read the application’s preference from a config file, instantiate and return an instance of the appropriate class.
It might be easy enough to slap a conditional around the instantiation to ensure that class_exists(), but MemcachedMessageStore extends PHP’s Memcached class. As a result, the class_exists() test will succeed–though instantiation will fail–if the memcached bindings for PHP aren’t installed.
Is there any other way to test whether a class can be instantiated properly? If it can’t, all I need to do is tell the user which features won’t be available to them, but let them continue one with the application.
As far as I can tell, this can’t be done short of PHP 5.3. What I did instead was to make the factory class check for the existence of
Memcachedbefore instantiating the class that extends it. It’s clumsy and far too brittle for my tastes, but it’s working for now. When we upgrade to 5.3, I’ll rework it a bit.