对象的行为就像一个数组? (PHP)
我在 ORM 中看到过类似的内容:
$b = new Book();
$b->limit(5)->get();
echo 'ID: ' . $b->id . '<br />';
echo 'Name: ' . $b->title . '<br />';
echo 'Description: ' . $b->description . '<br />';
echo 'Year: ' . $b->year . '<br />';
foreach ($b as $book)
{
echo 'ID: ' . $book->id . '<br />';
echo 'Name: ' . $book->title . '<br />';
echo 'Description: ' . $book->description . '<br />';
echo 'Year: ' . $book->year . '<br />';
echo '<br />';
}
一个对象怎么可能同时充当数组和对象?我怎样才能做到这一点? 我希望在 Book 的父类中看到一个新的 __magic 方法或其他东西,但我找不到任何东西,所以可能有一些关于 php 对象的基本知识我不知道。
有什么想法吗?提前致谢
I have seen something like this in an ORM:
$b = new Book();
$b->limit(5)->get();
echo 'ID: ' . $b->id . '<br />';
echo 'Name: ' . $b->title . '<br />';
echo 'Description: ' . $b->description . '<br />';
echo 'Year: ' . $b->year . '<br />';
foreach ($b as $book)
{
echo 'ID: ' . $book->id . '<br />';
echo 'Name: ' . $book->title . '<br />';
echo 'Description: ' . $book->description . '<br />';
echo 'Year: ' . $book->year . '<br />';
echo '<br />';
}
How is it possible that an object acts as both array and object? How can I accomplish that?
I was hoping to see a new __magic method or something in Book's parent class, but I couldn't find anything, so there might be something really basic about php objects that I don't know.
Any thoughts? Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
实现
Traversable
接口的对象(通过迭代器
或IteratorAggregate
) 支持foreach
构造,如果这就是您所说的“充当数组”的意思。例如:Objects that implement the
Traversable
interface (throughIterator
orIteratorAggregate
) support theforeach
construct, if that's what you mean by "acting as an array." Eg:您无需执行任何特殊操作即可将
foreach
与对象一起使用。来自对象迭代的 PHP 手册:
示例:
您的类不必按照其他地方的建议实现
Traversable
,事实上,上面的类不需要:您可以实现迭代器 或 IteratorAggregate 如果您需要更多地控制迭代的行为:
因为
Iterator
和IteratorAggregate
扩展Traversable
,您的类现在也将是Traversable
的实例,但如上所示,不需要迭代该对象。您还可以使用 ArrayObject 使对象表现得像一个混合体类和对象之间。或者您可以实现 ArrayAccess 以允许使用方括号访问类。您还可以将该类子类化为 PHP 提供的迭代器之一 。
进一步阅读:
You do not have to do anything special to use
foreach
with objects.From the PHP manual on Object Iteration:
Example:
Your class does not have to implement
Traversable
as suggested elsewhere and in fact, the class above doesn't:You can implement one of the Iterator or IteratorAggregate if you need more control over how the iteration should behave:
Because
Iterator
andIteratorAggregate
extendTraversable
, your class will now also be an instance ofTraversable
, but like shown above, it's not necessary for iterating the object.You can also use an ArrayObject to make the object behave like a hybrid between class and object. Or you can implement ArrayAccess to allow accessing the class with square brackets. You can also subclass the class to be one of the Iterators PHP provides.
Further reading: