在 PHP 中模拟值类型结构类 [英] Emulating a value type structure class in PHP

查看:35
本文介绍了在 PHP 中模拟值类型结构类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 PHP 中模拟结构类?即一个通过值而不是通过引用传递的类,所以它仍然可以被类型提示......

Is there any way to emulate a structure class in PHP? ie a class which passes by value and not by reference, so it can still be type hinted...

如果是这样,可以使用哪些不同的技术?最好的技术是什么?

And if so, what different techniques could be used? What's the best technique?

如果可以的话,您显然可以为 PHP 创建一个完全类型安全的层,是否有这样的层?有没有人有这方面的经验?

If this is possible you could obviously create a fully type safe layer for PHP, are there such layers? Has anyone had any experience with this?

推荐答案

对象总是通过引用传递.使它们作为副本传递的唯一方法是显式使用 clone 关键字(是的,无处不在).

Objects are always passed by reference. The only way to make them pass as a copy is to explicitly use the clone keyword (yes, everywhere).

我的建议是使用数组,它是值类型,因此总是被复制.由于您可以将其用作关联数组(例如字符串 -> 值),因此它也可能是一个对象.当然,缺点是你不能使用方法(但这就像一个结构体,所以你可能会对此感到满意).但是,没有办法强制执行类型安全.

My recommendation would be to use an array, which are value types and thus always copied. Since you can use it as an associative array (eg string -> value), it might as well be an object. The downside is, of course, you can't use methods (but that's like a struct so you may be happy with this). There is no way to enforce type safety, however.

但根据您的所有要求,老实说,PHP 听起来不是您喜欢的语言.

But with all your requirements it sounds like PHP isn't your kind of language, to be honest.

这篇关于在 PHP 中模拟值类型结构类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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