(这个问题使用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将同样导致错误,这是真的。然而,有一个正式的课堂对我来说更加僵化,但我不能真正地证明它。
使用每种方法的优点/缺点是什么,人们应该何时使用哪种方法?