Note to self: PHP object constructors never return false

Published June 13th, 2008

As part of my ongoing refactoring work (see previous post) and having decided to take a more active stand against broken windows syndrome I’ve been cleaning up various coding oddities as I’ve found them.

Today I came across (something like) this little snippet:

if( ! $obj = new myObject( $id ) )
{
  throw new Exception( 'Not a valid object' );
}

At first glance we might assume that the constructor attempts to populate the new object with some data loaded from (say) a database, but if no data matching the supplied ID is available, then the constructor returns false to indicate this. All very reasonable, right?

Except that it’s not possible to return false, or indeed any value, from a constructor because the ‘return value’ of the constructor is the object itself. Which means that the above snippet is redundant, because the expression will always evaluate to true.

It would’ve made more sense to throw an exception within the method that loads the data — and in fact this is exactly what happens, which makes the quoted code doubly redundant and even more inexplicable.

I don’t think I’m the one who’s responsible for this particular brain fart but it’s OK because the only other likely candidate left the company last year so I happily can blame it on him…

Get a Trackback link

5 Comments

  1. John on August 20, 2008

    Check out Andre’s hack at the bottom of the page:

    http://bugs.php.net/bug.php?id=9253&edit=1

  2. schmoove on September 1, 2008

    Andre’s hack will not work with PHP5:

    “Fatal error: Cannot re-assign $this”

  3. S on December 14, 2008

    Thank you for this post, I better learn some true error handling then.. damn ;)

  4. Jeff on May 12, 2011

    Even though this is old, I stumbled across it so other people might as well.

    Below is a workaround for not being able to return false but yet still ensure valid object creation.

    name = $name;
    }

    function getName() { return $this->name; }
    function __toString(){ return $this->name; }
    }
    ?>

    Instantiation:

    getMessage());
    }

    foreach($tests as $k => $v) {
    echo($v . “”);
    }
    ?>

  5. Jeff on May 12, 2011

    Well, I thought that would work better posting code like that, but the general idea was if a validation test fails, throw a new exception inside the constructor and then surround the object instantiation inside of a try/catch block.

    Hope this helps.

Leave a comment

Comment Policy: First time comments are moderated. Please be patient.

OpenID

Anonymous