Php interface

I'm sure some time ago I read a new PHP function, which was either a new magic method or a new interface so you can implement Arrayable methods.

eg,

interface Arrayable { public function toArray(); } 

Can I imagine it?

+8
arrays casting php interface magic-methods
source share
4 answers

Can I imagine it?

Yes.

+5
source share

This is not in PHP itself, but Laravel has an interface designed for this 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 .

+10
source share

Here it is (which is pretty useless IMO) http://php.net/manual/en/class.traversable.php

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

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

But it is not possible to handle indirect array conversion implicitly.

+2
source share

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

Also check out another predefined interface .

You can always write your own custom interface, and then you can enter a hint for it or test it with instanceof (see example # 4), as you indicated what you want to do in comment .

+1
source share

All Articles