PHP 中可以重载运算符吗?
具体来说,我想创建一个 Array 类并想重载 [] 运算符。
Specifically, I would like to create an Array class and would like to overload the [] operator.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果您使用 PHP5(您应该使用),请查看 SPL ArrayObject 类。 该文档不太好,但我认为如果您扩展 ArrayObject,您就会拥有“假”数组。
编辑:这是我的简单例子; 但恐怕我没有有价值的用例:
If you are using PHP5 (and you should be), take a look at the SPL ArrayObject classes. The documentation isn't too good, but I think if you extend ArrayObject, you'd have your "fake" array.
EDIT: Here's my quick example; I'm afraid I don't have a valuable use case though:
实际上,最佳的解决方案是实现ArrayAccess接口的四个方法:
http://php.net/manual/en/class.arrayaccess.php
如果您还想在“foreach”上下文中使用对象,则必须实现“Iterator”接口:
http://www.php.net/manual/en/class.iterator.php
Actually, the optimal solution is to implement the four methods of the ArrayAccess interface:
http://php.net/manual/en/class.arrayaccess.php
If you would also like to use your object in the context of 'foreach', you'd have to implement the 'Iterator' interface:
http://www.php.net/manual/en/class.iterator.php
PHP 的重载和运算符概念(请参阅重载和数组运算符) 与 C++ 的概念不同。 我不相信可以重载+、-、[]等运算符。
可能的解决方案
ArrayObject
对你来说太慢)。PHP's concept of overloading and operators (see Overloading, and Array Operators) is not like C++'s concept. I don't believe it is possible to overload operators such as +, -, [], etc.
Possible Solutions
ArrayObject
is too slow for you).对于 PHP 5.0+ 中的简单干净的解决方案,您需要实现
ArrayAccess
接口 并重写函数 offsetGet、offsetSet、offsetExists 和 offsetUnset。 您现在可以像数组一样使用该对象。示例(在 PHP7+ 中):
For a simple and clean solution in PHP 5.0+, you need to implements the
ArrayAccess
interface and override functions offsetGet, offsetSet, offsetExists and offsetUnset. You can now use the object like an array.Example (in PHP7+):
它似乎不是该语言的功能,请参阅此 bug。 但是,似乎有一个 包 可以让您进行某种重载。
It appears not to be a feature of the language, see this bug. However, it looks like there's a package that lets you do some sort of overloading.
简而言之,不; 我建议如果您认为需要 C++ 风格的重载,您可能需要重新考虑问题的解决方案。 或者也许考虑不使用 PHP。
用 Jamie Zawinski 的话来说,“你遇到问题并想,‘我知道!我会使用运算符重载!’ 现在你有两个问题。”
Put simply, no; and I'd suggest that if you think you need C++-style overloading, you may need to rethink the solution to your problem. Or maybe consider not using PHP.
To paraphrase Jamie Zawinski, "You have a problem and think, 'I know! I'll use operator overloading!' Now you have two problems."