views:

219

answers:

3

In PHP you can use square brackets on an element to access attributes:

$node = /* SimpleXMLElement */
$id = $node['id'];

What's weird is that $id isn't a string, It's another SimpleXMLElement. Why isn't it a string? I find myself using strval() all over the place on this.

How are the square brackets working? Can I do that with my own classes? I Haven't seen anything in the docs about this.

+3  A: 

You can provide Array like access to your object by implementing the ArrayAccess interface, which is part of the PHP Standard Library. This interface is one of those "even if you don't have the full PHP Standard Library extension installed, you still have this interface available in PHP 5" things.

By implementing this interface, and defining four methods for your class

public boolean offsetExists  ( string $offset  )
public mixed offsetGet ( string $offset )
public void offsetSet ( string $offset , string $value )
public void offsetUnset ( string $offset )

you should be able to use square brackets with your instantiated objects.

As for SimpleXML itself, I'm not sure if it actually implements the ArrayAccess interface, or if there's something else going on behind the scenes in the PHP source that gives it these super powers.

Alan Storm
A: 

I guess it's the magic method __get()

Edit: I think I guessed wrong. Didn't know of the Array Access interface yet.

daddz
+1  A: 

I believe you can extend the SimpleXML class, and implement the ArrayAccess in that.

WishCow