Created
August 30, 2015 09:19
-
-
Save sword-jin/09e2e7d2dff20fafb8bd to your computer and use it in GitHub Desktop.
laravel 中 collection.php 的部分实现,例如..使用 IteratorAggregate, Countable 接口
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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