开发者

PHP - constructor function doesn't 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;
  }

}

$f开发者_如何学JAVAoo = 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.


Constructor is not supposed to return anything.

If you need to validate data before using the to create an object, you should use a factory class.

Edit: yeah , exceptions would do the trick too, but you should not have any logic inside the constructor. It becomes a pain for unit-testing.


You can try

<?php

function __construct($something = false){ 
    $this->stuff = $something; 
}

static function init($something = false){
    $stuff = is_int($something) ? &getStuff($something) : $GLOBALS['something'];
    return $stuff ? new self($stuff) : false;
}


$foo = foo::init(435);  // 435 does not exist
if(!$foo) die();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜