20

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?

hakre
  • 193,403
  • 52
  • 435
  • 836
gawpertron
  • 1,867
  • 3
  • 21
  • 37

4 Answers4

26

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.

coatesap
  • 10,707
  • 5
  • 25
  • 33
  • 2
    I was kind of thinking of a native interface that you could then typecast objects to an array i.e. `$array = (array) $object;` – gawpertron Mar 21 '14 at 15:08
  • namespace Illuminate\Contracts\Support; – alexeydemin Oct 02 '16 at 23:15
  • @gawpertron btw you can do that, it will result in array of property values keyed by property names - you can then access public properties, private&protected are prefixed in this conversion - more on that here in official docs: https://www.php.net/manual/en/language.types.array.php#language.types.array.casting – jave.web May 24 '19 at 16:06
17

Was I imagining it?

Yes.

salathe
  • 51,324
  • 12
  • 104
  • 132
2

You are probably thinking of the iterator interface. If you create a class that implements this you can iterate over it as if it is an array. For example, you can use it in a foreach() loop.

Also take a look at the other predefined interfaces.

You can always write your own arrayable interface and then you can type hint for it or check it with instanceof (see example #4) as you indicated you wanted to do in your comment.

Community
  • 1
  • 1
vascowhite
  • 18,120
  • 9
  • 61
  • 77
  • http://www.php.net/manual/en/class.serializable.php has the same idea as the Arrayable interface. It's not about making an object traversable, but being able to return a representation of the object as an Array. – gawpertron Aug 07 '12 at 08:13
  • Or type casting to an array ie `$foo = (array) $arrayableObject` – gawpertron Aug 07 '12 at 08:15
  • Then just write a toArray() method. You are best placed to know how your object should be represented as an array. I don't think PHP could be expected to guess that for you. – vascowhite Aug 07 '12 at 08:17
  • I plan to, but to check if the object is an `interfaceof` of a standard interface would be tidy. – gawpertron Aug 07 '12 at 08:19
2

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.

calumbrodie
  • 4,722
  • 5
  • 35
  • 63