Constructors that can fail

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
This is just a quickie but it's been buggign me for a while now and as
far as I can tell the PHP manual doesn't have anything to say on the

I have a situation where I have constructors that can fail.  For
example ones that fetch a database row and populate the instance
properties with the returned results.  If, for example, an invalid ID
gets passed in the new call, then the result can be that no row is
returned and the result is my newly created object has invalid

Instead of this I'd like for the instance to just be set to NULL if
something goes wrong in the constructor.  For example, if I do

$item = new Item ($id)

then I want $item to contain a valid instance of Item if the ID was
valid, but for $item to be NULL if it wasn't.  Is this possible with
PHP, if so, then how?

Re: Constructors that can fail

Gordon wrote:

Quoted text here. Click to load it

Use a factory design pattern. See or have a look at some
programming books.

That way, you'll be able to return an instance, or a NULL value.

Iván Sánchez Ortega -ivansanchez-algarroba-escomposlinux-punto-org-

Ama un solo día y el mundo entero habrá cambiando.- Robert Browning.

Re: Constructors that can fail

On Feb 15, 4:07 pm, Iv=E1n S=E1nchez Ortega <ivansanchez-...@rroba-> wrote:
Quoted text here. Click to load it

Thanks.  i was hoping it'd be something simple like unset ($this) or
$this = NULL, but the former doesn't seem to do anything and the
latter causes a fatal error.

Re: Constructors that can fail

Quoted text here. Click to load it

Use an exception inside the constructor in conjunction with a factory

class Foo {

    protected function __construct($id) {
        if($this->loadData($id) =3D=3D false)
            throw new Exception();

    public static function getFoo($id) {
        try {
            $obj = new self($id);
        } catch (Exception $e) {
            $obj = null;

        return $obj;


Site Timeline