Is there a way to prevent object creation within its constructor, so that:
$object = new Foo();
echo $object; // outputs: NULL
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.
class Foo {
public function __construct() {
throw new Exception('Could not finish constructing');
}
}
try {
$object = new Foo();
} catch (Exception $e) {
echo $e->getMessage();
}
Impossible, but you can proxify the creation.
<?php
class Foo {
private function __construct() {}
static function factory($create=False) {
if ($create) {
return new Foo;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With