【发布时间】:2014-04-01 16:10:05
【问题描述】:
在阅读各种教程时,我注意到这两种不同的方法,我很好奇幕后发生了什么。
第一种方法在构造函数中做所有事情——所有事情都是设置变量,或者在这种情况下调用类的方法来做某事。第二种方法在构造函数中调用私有方法来做同样的事情。什么时候一种方式优于另一种方式?我知道微优化是邪恶的,但是在学术层面上调用私有方法会慢一点吗?
这是第一种方法的代码示例(这是一些 zf2 代码):
class LoginForm extends Form
{
public function __construct($name = null) {
// we want to ignore the name passed
parent::__construct('login-form');
$this->setAttribute('method', 'post');
$this->add(array(
'name' => 'username',
'attributes' => array(
'type'=> 'text',
),
'options' => array(
'label' => 'User Name',
),
)); ...
VS 这个:
class LoginForm extends Form
{
public function __construct($name = null) {
// we want to ignore the name passed
parent::__construct('login-form');
$this->setAttribute('method', 'post');
$this->addElements();
}
private function addElements() {
$this->add(array(
'name' => 'username',
'attributes' => array(
'type'=> 'text',
),
'options' => array(
'label' => 'User Name',
),
)); ...
不明白为什么会被标记。我没有问哪种方式更好我看到了一些我不完全理解的东西,想听听一些可能的原因为什么一个程序员可能会用一种方式来做,而另一个以另一种方式做到了。接受的答案对我很有帮助,因为它还指出了一种方法可能可能出现的设计问题。
【问题讨论】:
-
保持构造函数简单是个好习惯。
-
我认为大多数人会倾向于第二种方法以提高可读性。如果 addElements 公开,你的重构就会减少。
-
所以它主要是为了可读性?这是有道理的。
-
我同意,第二种方法很可能是首选。不仅是为了可读性,也是为了可扩展性。
-
是不是更慢了——再次只是为了满足我的好奇心。我知道这么微小的性能优势不值得造成无法维护的混乱。
标签: php oop constructor