What are some common PHP interfaces used for list operations?
When working with lists in PHP, it is common to use interfaces to define the behavior of list operations. Some common PHP interfaces used for list operations include Iterator, ArrayAccess, and Countable. These interfaces provide methods that allow you to iterate over a list, access elements by index, and get the number of elements in a list.
// Example implementation using Iterator interface
class MyList implements Iterator {
private $data = [];
public function __construct(array $data) {
$this->data = $data;
}
public function current() {
return current($this->data);
}
public function key() {
return key($this->data);
}
public function next() {
next($this->data);
}
public function rewind() {
reset($this->data);
}
public function valid() {
return key($this->data) !== null;
}
}
// Example usage
$list = new MyList([1, 2, 3]);
foreach ($list as $item) {
echo $item . "\n";
}