我想实现一个像数组一样的对象。它应该以这种方式使用:是否可以在PHP中实现类似数组的对象?
$var = new CustomCollection(retrieveFromWebService());
echo $var[0]; // legal
$var[0] = 'a'; // illegal
这可以使用魔术方法或其他机制在PHP中完成吗?
我想实现一个像数组一样的对象。它应该以这种方式使用:是否可以在PHP中实现类似数组的对象?
$var = new CustomCollection(retrieveFromWebService());
echo $var[0]; // legal
$var[0] = 'a'; // illegal
这可以使用魔术方法或其他机制在PHP中完成吗?
你的CustomCollection
类将需要实现内置的ArrayAccess
interface。
参见:http://code.google.com/p/phpraise/source/browse/trunk/phpraise/core/collection/RaiseCollection.php
我觉得ArrayAccess是你在找什么。
[PHP对象像数组]可能重复(http://stackoverflow.com/questions/2007695/php-object-like-array) – 2011-03-14 14:31:33
@Felix:哎呀,对,对不起。 – pyon 2011-03-14 14:33:28