如何在 php 中创建具有重复键而不是默认哈希的数据结构?
我想创建包装类,它将启用键重复,而默认哈希不允许。类应该使用php5中引入的成员重载机制,因此它会模仿标准哈希的所有行为。例如,我想要像
$var => obj( :values_arr -> array(
obj(:key -> 'mykey', :value -> 'val1'),
obj(:key -> 'mykey', :value -> 'val2')
)
)
如果我想获得 $var['mykey'],它应该返回 array('val1', 'val2'),但是如果我想用新的 'mykey' => 扩展 obj ; “值”对,我称之为
$val['mykey'][] = 'value'
主要思想是保留哈希的行为,并且在尝试使用现有密钥分配值后,它不会被覆盖,而是附加到列表中。
你会如何模仿 php5(5.3 之前)中的其他数据结构?您想分享任何已知的解决方案或示例吗?
I want to create wrapper class, which will enable keys duplicates while default hash does not allow it. Class should use member overloading mechanism introduced in php5, so it would imitate all the behavior standard hash has. For example, I want to have smth like
$var => obj( :values_arr -> array(
obj(:key -> 'mykey', :value -> 'val1'),
obj(:key -> 'mykey', :value -> 'val2')
)
)
If I want to get $var['mykey'], it should return array('val1', 'val2'), but if I want to extend obj with new 'mykey' => 'value' pair, I would call
$val['mykey'][] = 'value'
Main idea is that behavior of the hash was preserved and after attempt to assign value to using existing key, it wouldn't be overwritten, but appended to the list.
How would you imitate other data structures in php5 (before 5.3)? Are there any known solutions or examples you want to share?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
像这样,
但整个想法对我来说看起来有点奇怪。你能解释一下为什么你需要这个吗?
我不清楚为什么需要运算符作为 AST 中的键
也许这样的结构会更方便
like this
but the whole idea looks a bit odd to me. Can you explain why you need this?
it's not clear for me why you need operators as keys in your AST
perhaps a structure like this would be more convenient
实现数组语法
您可以使用
ArrayAccess
接口我还实现了
IteratorAggregate< /code> 允许迭代所有单个元素。
测试代码
测试输出
You can achieve the array syntax
with the
ArrayAccess
interfaceI also implemented
IteratorAggregate
to allow iteration over all single elements.Test Code
Test Output