PHP 中的值对象与关联数组
2022-08-30 12:14:10
(这个问题使用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
使用每种方法的利弊是什么,人们什么时候应该使用哪种方法?