Can a constructor fail?

Is there a way for a constructor to ‘fail’, or not return an object?

I’m thinking of a situation where arguments are passed to the constructor, e.g.;


// valid coordinates, the object is created
$validPlace = new geoLocation(-34.1232, 116.3422);

// invalid coordinates, the object is NOT created
$invalidPlace = new geoLocation(999, 999);

I can’t just return FALSE, because constructors don’t allow return values.

I’m aware that validation should be done with a special validating class, but I’m curious as to whether what I want to do is possible.

The standard way in Java and other languages is to throw some kind of exception, which in turn has to be caught and handled by the code that attempts to create the object. I don’t know enough about PHP OO, but I can give you a basic example in Java:


public class SomeClass {
   private String _data;
   public SomeClass(String param) {
      if(param.length() == 0)
         throw new IllegalArgumentException("Param too short!");
      else
         _data = param;
   }
}

In the calling code:


try {
   SomeClass bob = new SomeClass("");
} catch(IllegalArgumentException ex) {
   System.err.println(ex.message());
}

My syntax is probably a bit sloppy but that’s the general idea.

Cheers,
D.

Alternatively, if the values passed to the constructor are invalid, you could set a publicly-accessible property that flags it as invalid, and leave it uninitialised.

Cheers,
D.

Could anyone supply a PHP way to do with try/throw/catch?

Solution for killing the object:

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

Thanks everyone, but it’s beginning to look like what I want isn’t possible.

I can’t unset($this) within the class, http://au2.php.net/manual/en/function.unset.php says ‘Note: It is not possible to unset $this inside an object method since PHP 5.’

I can’t set $this to NULL or FALSE, http://bugs.php.net/bug.php?id=27659 says ‘Actually this is expected behavior. We explicitly decided to have $this
being readonly because of internal problems with the new engine.’

Perhaps I need to look at factory?


<?php

class TestException
{
    public function __construct ()
    {
        throw new Exception( 'Failed!' );
    }
}

try {
    $c = new TestException();
} catch ( Exception $e ) {
    var_dump( $e );
}