讨论数量: 
            
            
    
            <?php
use App\Models\Topic;
Route::get('test/{topic}', function (Topic $topic){
    dump($topic->replies);
    foreach($topic->replies as $reply)
    {
        dump($reply);
    }
});打印显示

可以看到这个item是protected,但是foreach的时候还是拿到它了,而且本来是应该输出一个数组,这里却输出了数组成员
额,文档第一句话就有了提供像访问数组一样访问对象的能力的接口。
只要你对象实现的 ArrayAccess 接口,那么你就可以像数组一样遍历,
就像你上面那样的, 明显你打印的$topic->replies 是 Illuminate\Support\Collection 对象
foreach($topic->replies as $reply)
{
        dump($reply);
}你再去看看 Illuminate\Support\Collection 源码就知道了,实现的ArrayAccess 方法里面 offsetGet, offsetSet, offsetExists, offsetUnset 全都是对 item 处理
 
           
         
             
                     
                     
             
             
             
             
           
           关于 LearnKu
                关于 LearnKu
               
                     
                     
                     粤公网安备 44030502004330号
 粤公网安备 44030502004330号 
 
推荐文章: