Note to self: PHP object constructors never return false
Published June 13th, 2008As 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…
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