PHP Arrayable Interface

It's not in PHP itself, but Laravel has an interface that is intended for that exact purpose:

<?php namespace Illuminate\Contracts\Support;

interface Arrayable {

    /**
     * Get the instance as an array.
     *
     * @return array
     */
     public function toArray();

}

Note: In Laravel v4 the namespace was Illuminate\Support\Contracts and the interface name was ArrayableInterface.


Was I imagining it?

Yes.

  • There is no interface (PHP 5.4 or otherwise) within PHP for handling casting to an array.

  • PHP 5.4.0 introduced the JsonSerializable interface, perhaps you're thinking of that?

  • There's also a draft RFC (one of several related) that suggests a __toArray() method; see Request for Comments: Scalar Type Casting Magic Methods


There's this (which is fairly useless IMO) http://php.net/manual/en/class.traversable.php

and also this (which does come in handy but always requires a type check before using it)

http://php.net/manual/en/function.iterator-to-array.php

But no way to handle object to array conversion implicitly.