How can I let the $foo
variable below know that foo should be false?
我怎么能让下面的$ 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 :(
2 个解决方案
#1
32
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.
您还可以扩展例外。
#2
4
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.
编辑:是的,异常也可以做到这一点,但你不应该在构造函数中有任何逻辑。它成为单元测试的痛苦。
#1
32
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.
您还可以扩展例外。
#2
4
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.
编辑:是的,异常也可以做到这一点,但你不应该在构造函数中有任何逻辑。它成为单元测试的痛苦。