PHP中的值对象的示例是什么

PHP中的值对象的示例是什么

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

问题描述

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

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

值对象仅仅是字符串吗?

解决方案

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

bar = new Foo
baz = new Foo

bar == baz  // false

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

bar = new Foo
baz = bar

bar == baz  // true

现在:

这将是值对象"的演示:

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

address1 == address2  // true

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

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:

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:

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中的值对象的示例是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 03:59