Is there a way to prevent object creation within its constructor, so that:
$object = new Foo();
echo $object; // outputs: NULL
Is there a way to prevent object creation within its constructor, so that:
$object = new Foo();
echo $object; // outputs: NULL
Impossible, but you can proxify the creation.
Nope, not possible; the
new
keyword always returns an instance of the class specified, no matter what you attempt to return from the constructor. This is because by the time your constructor is called, PHP has already finished allocating memory for the new object. In other words, the object already exists at that point (otherwise, there's no object on which to call the constructor at all).You could raise errors or throw exceptions from the constructor instead, and handle those accordingly.
If you are try to stop an object from instantiating depending on a few conditions, then why not create a condition before you even hit the PHP
new
and instantiate the class?What I mean is, say in your example:
You could wrap it in a function that does the validation work for you or just simply an if statement if you are only gonna instantiate the class once.
Like this:
if you need to instantiate that multiple times then wrap it in a function and pass the parameters to your class.
Hope this helps.
You could implement a factory to do the object creation for you. If you are using PHP 5.3.0+ then you will have access to a feature called Late Static Binding that makes this easy.
If you are using a version of PHP prior to 5.3.0 then things get a bit more complicated as late static binding and get_called_class () are not available. However, PHP 5 does support reflection and you can use it to emulate late static binding. Alternatively you can implement a separate factory class and pass it an argument telling it what kind of object you want to initialize.
Another approach is to get your constructor to throw an exception if it fails and handle it with a catch block. However this method can get kind of hairy if you are doing it a lot and it should really only be used when you normally expect object creation to succeed (in other words, if creation failure is an exceptional circumstance).
The factory approach has additional advantages, for example it can hold a cache of objects that you've already created and if you attempt to create the same object twice it will simply pass you a reference the already-initialized object instead of creating a new one. This eliminates memory and processing overhead inherent in object creation, especially if creation involves a time-intensive task such as a complex SQL query
Simply throw an exception: