PHP - 构造函数不返回false

Ale*_*lex 22 php constructor class object

我怎么能让$foo下面的变量知道foo应该是假的?

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 :(
Run Code Online (Sandbox Code Playgroud)

web*_*ave 34

您无法从构造函数返回值.您可以使用例外.

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');
    }
}
Run Code Online (Sandbox Code Playgroud)

并在您的实例化代码中:

try {
    $foo = new foo(435);
} catch (Exception $e) {
    // handle exception
}
Run Code Online (Sandbox Code Playgroud)

您还可以扩展例外.


ter*_*ško 5

构造函数不应该返回任何东西。

如果您需要在使用创建对象之前验证数据,则应该使用工厂类。

编辑:是的,异常也可以解决问题,但是构造函数中不应该有任何逻辑。这对于单元测试来说是一种痛苦。