(这个问题以PHP为背景,但并不仅限于PHP。例如任何具有内置哈希的语言也是相关的)
让我们看一下这个例子(PHP):
function makeAFredUsingAssoc()
{
return array(
'id'=>1337,
'height'=>137,
'name'=>"Green Fred");
}
对比:
class Fred
{
public $id;
public $height;
public $name;
public function __construct($id, $height, $name)
{
$this->id = $id;
$this->height = $height;
$this->name = $name;
}
}
function makeAFredUsingValueObject()
{
return new Fred(1337, 137, "Green Fred");
}
当然,方法#1更加简洁,但是它很容易导致错误,例如
$myFred = makeAFredUsingAssoc();
return $myFred['naem']; // notice teh typo here
当然,人们可能会争论$myFred->naem
同样会导致错误,这是正确的。但是,对我来说,有一个正式的类感觉更加严格,但我无法真正证明它。使用每种方法的优缺点是什么,人们应该在何时使用哪种方法?
NOTICE
,其中包含PHP Notice: Undefined index: doesntExist
。 - Corey Ballou