值对象与PHP中的关联数组 [英] Value objects vs associative arrays in PHP

查看:95
本文介绍了值对象与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?

推荐答案

在表面上,这两种方法是等效的.但是,使用类时,您将获得大多数标准的OO好处:封装,继承等.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆