2

Why does the construct function return the object, and not the return value (boolean) ?

class A{

  function __construct($stuff){

    return ($this->load($stuff) !== false);
  }
}

$aaa = new A($stuff);

if(!$aaa)  die('error'); // never happens


print_r($aaa); // it's a object...
NullUserException
  • 83,810
  • 28
  • 209
  • 234
Boxxy
  • 21
  • 1
  • 2
  • first answer of this question will help you http://stackoverflow.com/questions/2214724/php-constructor-to-return-a-null – TeaCupApp Sep 08 '11 at 23:38

3 Answers3

4

Constructor: You are doing it wrong.

Constructors do what their name implies: construct a new instance of an object. The only thing that makes sense for a constructor to return is thus an instance of that object. Note that you'll almost never see a constructor with an explicit return statement 1.

The cleaner way to accomplish what I believe you want to do is to use exceptions:

class A {
    function __construct($stuff) {
        if ($this->load($stuff) === false) {
            throw new Exception('Unable to load');
        }
    }
}

try {
    $aaa = new A($stuff);
} catch (Exception $e) {
    die('error' . $e->getMessage());
}

1 They are allowed, so there might be a compelling reason for that. Just can't think of it right now.

NullUserException
  • 83,810
  • 28
  • 209
  • 234
1

Constructor can only return a new instance of an object. You could try using a static function call that would call the constructor and return false or the new object.

Logan Bailey
  • 7,039
  • 7
  • 36
  • 44
0

The return value of the constructor is ignored by the new operator. The new operator will always return an object. When having code like

class A {
    function __construct() {
        return 1;
    }
 }
 class B extends A {
     function __construct() {
         var_dump(parent::__construct());
     }
 }
 new B();

you can see that the constructor has a return value. Writing such code makes, of course, little sense.

For handling errors inside a constructor you'd have to use exceptions. An alternative approach is some kind of factory method.

class C {
    private function __construct() { }
    private function init() {
        if (something_goes_wrong()) {
            return false;
        }
     }

     public static createInstance() {
         $retval = new self;
         if (!$retval->init()) {
             return false;
         }
         return $retval;
     }
}
johannes
  • 15,807
  • 3
  • 44
  • 57