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

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

then why is return allowed in them?
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;
     }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.