Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Arrayable Interface

I'm sure I read a while back about a new feature of PHP that was either a new magic method or a new interface so that you could implement Arrayable methods.

eg

interface Arrayable
{
    public function toArray();
}

Was I imagining it?

like image 237
gawpertron Avatar asked Aug 07 '12 08:08

gawpertron


2 Answers

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.

like image 160
coatesap Avatar answered Sep 20 '22 16:09

coatesap


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

like image 32
salathe Avatar answered Sep 19 '22 16:09

salathe