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.
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.
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.’