Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Breaking the constructor

Tags:

oop

php

Is there a way to prevent object creation within its constructor, so that:

$object = new Foo();
echo $object; // outputs: NULL
like image 435
Emanuil Rusev Avatar asked Jan 26 '11 11:01

Emanuil Rusev


2 Answers

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();
}
like image 152
BoltClock Avatar answered Sep 23 '22 06:09

BoltClock


Impossible, but you can proxify the creation.

<?php

class Foo {
    private function __construct() {}

    static function factory($create=False) {
        if ($create) {
            return new Foo;
        }
    }
}
like image 22
Xavier Barbosa Avatar answered Sep 22 '22 06:09

Xavier Barbosa