PHP 中的值对象与关联数组 [英] Value objects vs associative arrays in PHP
问题描述
(这个问题使用 PHP 作为上下文,但不仅限于 PHP.例如,任何带有内置哈希的语言也是相关的)
(This question uses PHP as context but isn't restricted to PHP only. e.g. Any language with built in hash is also relevant)
让我们看一下这个例子(PHP):
Let's look at this example (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当然更简洁,但是很容易导致诸如
Method #1 is of course terser, however it may easily lead to error such as
$myFred = makeAFredUsingAssoc();
return $myFred['naem']; // notice teh typo here
当然,有人可能会争辩说 $myFred->naem
同样会导致错误,这是真的.然而,正式的课程对我来说感觉更僵硬,但我真的无法证明它是合理的.
Of course, one might argue that $myFred->naem
will equally lead to error, which is true. However having a formal class just feels more rigid to me, but I can't really justify it.
使用每种方法的利弊是什么?人们应该何时使用哪种方法?
What would be the pros/cons to using each approach and when should people use which approach?
推荐答案
在表面之下,这两种方法是等效的.但是,您在使用类时可以获得大部分标准面向对象的好处:封装、继承等.
Under the surface, the two approaches are equivalent. However, you get most of the standard OO benefits when using a class: encapsulation, inheritance, etc.
另外,请看以下示例:
$arr['naem'] = 'John';
完全有效,可能很难找到错误.
is perfectly valid and could be a difficult bug to find.
另一方面,
$class->setNaem('John');
永远不会工作.
这篇关于PHP 中的值对象与关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!