PHP中的不可变对象? [英] Immutable objects in PHP?

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

问题描述

创建在PHP中无法更改的对象是一个好主意吗?

Is it a good idea to create objects that cannot be changed in PHP?

例如,具有setter方法的date对象,但它们将始终返回新的对象的实例(具有更改的日期)。

For example a date object which has setter methods, but they will always return a new instance of the object (with the modified date).

这些对象会使使用该类的其他人感到困惑吗,因为在PHP中,您通常希望对象发生变化?

Would these objects be confusing to other people that use the class, because in PHP you usually expect the object to change?

示例

$obj = new Object(2);

$x = $obj->add(5); // 7
$y = $obj->add(2); // 4


推荐答案

一个不可变的对象在其后不能更改最初的创建过程,因此使用setter方法没有任何意义,因为它违反了该基本原则。

An immutable object cannot be change after its initial creation so having setter methods makes no sense as it goes against that base principle.

您可以通过操纵类成员的可见性并覆盖魔术__set()方法,实现一些变通方法来模拟PHP中的不可变性,但是由于不可变性不是它的功能,因此不能保证其不可变。语言。我相信有人曾经写过一个扩展程序来在PHP中提供不可变的值类型,所以您可以用google搜索它。

You could implement some workarounds to simulate immutability in PHP by manipulating class member visibility and overriding the magic __set() method but its not guaranteed immutable as immutability is not a feature of the language. I believe someone once wrote an extension to provide an immutable value type in PHP though so you could google for that.

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

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