PHP中的值对象的示例是什么? [英] What is an example of a Value Object in PHP?

查看:107
本文介绍了PHP中的值对象的示例是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了很多C#值对象的示例,并且我了解它是一个由其值标识的对象".如果值更改,则该对象为新".

但是,当涉及到PHP时,这似乎没有任何意义……要么就是我没有建立连接.

值对象仅仅是字符串吗?

解决方案

将其置于上下文中,在许多OO语言中,对象通过其 identity 进行比较.用伪代码:

bar = new Foo
baz = new Foo

bar == baz  // false

即使您仅查看它们的,即使这两个对象基本相同,但由于它们是单独的实例,因此也不认为它们是相同的.演示:

bar = new Foo
baz = bar

bar == baz  // true

现在:

在计算机科学中,价值对象是一个小的简单对象,例如金钱或日期范围,其相等性不是基于身份的.

http://en.wikipedia.org/wiki/Value_object

这将是值对象"的演示:

address1 = new Address('Main street 42')
address2 = new Address('Main street 42')

address1 == address2  // true

由于值相同,因此即使它们是单独的实例,两个对象也被视为相等.

PHP没有单独的值对象"概念,它只有一种类型的对象.它的比较运算符可以做到这一点:

使用比较运算符(==)时,将以简单的方式比较对象变量,即:如果两个对象实例具有相同的属性和值,并且属于同一类,则它们是相等的.

http://www.php.net/manual/zh_CN/language.oop5.object-comparison.php

例如:

$address1 = new Address('Main street 42');
$address2 = new Address('Main street 42');

$address1 == $address2;  // true     equal...
$address1 === $address2;  // false   ...but not identical

I have read plenty of C# examples of Value Objects, and I understand that it is an "object" that is identified by it's values. If a value changes, the object is "new".

However, that doesn't seem to make sense when it comes to PHP...either that, or I'm just not making the connection.

Is a Value Object just a string?

解决方案

To put this into context, in many OO languages, objects are compared by their identity. In pseudocode:

bar = new Foo
baz = new Foo

bar == baz  // false

Even though both objects are basically the same if you just look at their values, they're not considered to be identical, because they are separate instances. To demonstrate:

bar = new Foo
baz = bar

bar == baz  // true

Now:

In computer science, a value object is a small simple object, like money or a date range, whose equality isn't based on identity.

http://en.wikipedia.org/wiki/Value_object

This would be a demonstration of "value objects":

address1 = new Address('Main street 42')
address2 = new Address('Main street 42')

address1 == address2  // true

Because the values are the same, both objects are considered equal, even if they're separate instances.

PHP does not have a separate concept of "value objects", it only has one type of object. Its comparison operator can make that distinction though:

When using the comparison operator (==), object variables are compared in a simple manner, namely: Two object instances are equal if they have the same attributes and values, and are instances of the same class.

http://www.php.net/manual/en/language.oop5.object-comparison.php

E.g.:

$address1 = new Address('Main street 42');
$address2 = new Address('Main street 42');

$address1 == $address2;  // true     equal...
$address1 === $address2;  // false   ...but not identical

这篇关于PHP中的值对象的示例是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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