Tuesday, 28 August 2018

PHP - The constructor function does not return false

How can I let the $foo variable below know that foo should be false?

class foo extends fooBase{

  private
    $stuff;

  function __construct($something = false){
    if(is_int($something)) $this->stuff = &getStuff($something);
    else $this->stuff = $GLOBALS['something'];

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

}

$foo = new foo(435);  // 435 does not exist
if(!$foo) die(); // <-- doesn't work :(


You cannot return a value from the constructor. You can use exceptions for that.
function __construct($something = false){
    if(is_int($something)) $this->stuff = &getStuff($something);
    else $this->stuff = $GLOBALS['something'];

    if (!$this->stuff) {
        throw new Exception('Foo Not Found');
    }
}

And in your instantiation code:
try {
    $foo = new foo(435);
} catch (Exception $e) {
    // handle exception
}

You can also extend exceptions.

0 comments:

Post a Comment