Skip to content

Instantly share code, notes, and snippets.

@sword-jin
Created August 30, 2015 09:19
Show Gist options
  • Save sword-jin/09e2e7d2dff20fafb8bd to your computer and use it in GitHub Desktop.
Save sword-jin/09e2e7d2dff20fafb8bd to your computer and use it in GitHub Desktop.
laravel 中 collection.php 的部分实现,例如..使用 IteratorAggregate, Countable 接口
<?php
class Library implements IteratorAggregate, Countable
{
protected $books;
public function __construct(array $books)
{
$this->books = $books;
}
public function getIterator()
{
return new ArrayIterator($this->books);
}
public function count()
{
return count($this->books);
}
}
class Book
{
public $title;
public function __construct($title)
{
$this->title = $title;
}
}
$books[] = new Book('Book One');
$books[] = new Book('Book Two');
$books[] = new Book('Book Three');
$lib = new Library($books);
foreach ($lib as $book) {
echo $book->title . PHP_EOL;
}
echo $lib->count($books);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment