Catch a PHP Object Instantiation Error

Posted by Rob Wilkerson on Stack Overflow See other posts from Stack Overflow or by Rob Wilkerson
Published on 2010-06-10T12:27:46Z Indexed on 2010/06/10 12:43 UTC
Read the original article Hit count: 197

Filed under:
|
|

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:

  • DatabaseMessageStore
  • FileMessageStore
  • MemcachedMessageStore
  • 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.

Thanks.

© Stack Overflow or respective owner

Related posts about php

Related posts about php5