3v4l.org

run code in 300+ PHP versions simultaneously
<?php interface Arrayable { public function toArray(); } class Item implements Arrayable { protected $attributes = array(); protected $someParameter = true; public function __construct($attributes) { $this->attributes = $attributes; } public function toArray() { return $this->attributes; } public function __toArray() { return $this->toArray(); } } class ItemCollection implements Arrayaable { protected $items = array(); public function addItem(Item $item) { $this->items[] = $item; } public function toArray() { $result = array(); foreach ($this->items as $item) { $result[] = $item->toArray(); } return $result; } public function __toArray() { return $this->toArray(); } } $array = array('foo' => 'bar', 'baz' => 'qux'); $item = new Item($array); print_r((array) $item); print_r($item->toArray()); $collection = new ItemCollection(); $collection->addItem($item); $collection->addItem($item); print_r((array) $collection); print_r($collection->toArray());

preferences:
37.66 ms | 402 KiB | 5 Q