【发布时间】:2012-10-03 18:28:23
【问题描述】:
我知道有很多与此相关的问题。但是,我没有设法找到简单问题的答案(我不是在询问从构造函数返回值的问题,我认为我理解构造函数应该返回什么)。
有什么理由避免在__construct 中使用return?
或者这种完全可以接受的编码风格在未来不会因为return而中断:
class A {
protected $tristate = null;
function __construct() {
// Constructor returns instance of class automatically
// no need to `return $this`
}
protected function Logic() {
return rand(0, 1) === 1;
}
}
class B extends A {
function __construct() {
parent::__construct();
if ($this->Logic()) return;
$this->tristate = true;
}
}
上面的一个已经过测试并且它按预期工作(在我的开发环境中),它将父 $tristate var 50/50 设置为 NULL/TRUE,但它会在未来工作吗?使用void return 在构造函数中间返回时出现的任何问题。
我想到的另一件事是我应该使用return $this 而不是普通的return,这通常是无效的,但PHP 似乎无论如何都会返回实例,答案很可能是return $this 和普通的return 都只是一样好。
【问题讨论】:
-
这个类只是一个简化的例子,因为我的问题不是关于从其构造函数返回除普通类实例之外的东西(任何特殊的)。我在构造函数中间询问
returnìng 以及在构造函数中间返回 void(似乎被 PHP 引擎替换)可能出现的问题。
标签: php oop constructor