【发布时间】:2010-09-24 21:30:13
【问题描述】:
在使用 OO PHP 时,获取/设置变量的哪种方式在语义上最“正确”?
据我所知,有getter/setter,按引用传递和按值传递。按值传递比按引用传递要慢,但按引用传递实际上会操纵变量的内存。假设我想这样做(或者至少不介意),这在语义上更正确/更有效?
在处理围绕对象传递的变量时,我一直在使用 getter/setter 类型。我发现这在语义上是正确的并且更容易“阅读”(没有长列表函数参数)。但我认为它的效率较低。
考虑这个例子(当然是人为的):
class bogus{
var $member;
__construct(){
$foo = "bar"
$this->member = $foo;
$this->byGetter();
$this->byReference($foo);
$this->byValue($foo);
}
function byGetter();{
$baz =& $this->member;
//set the object property into a local scope variable for speed
//do calculations with the value of $baz (which is the same as $member)
return 1;
}
function byReference(&$baz){
//$baz is already set as local.
//It would be the same as setting a property and then referencing it
//do calculations with the value of $baz (same as $this->member)
return 1;
}
function byValue($baz){
//$baz is already set as local.
//It would be the same as setting a property and then assigning it
//do calculations with the value of $baz
return 1;
}
}
【问题讨论】:
-
这有什么实际用途吗?给它一个基准,看看是否有显着差异。如果没有,请保持简单(且可读)。
-
好吧,这只是一个例子来说明我在说什么。例如,我知道编写一个带有 8 个通过引用传递的参数的函数会更快,但它非常难看。相反,如果我使用对象属性将变量从一件事传递到另一件事,那么它会更干净,但速度更慢。那么在语义上哪个更可取?