how to use object as array like in simplexml

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
I am new to PHP, and I'm trying to implement something similar to
SimpleXML. The following code demonstrates an example of what I'm
trying to achieve:

$xmlstr = <<<XML
    <foo att="val1">bar1</foo>
    <foo att="val2">bar2</foo>

$xml = new SimpleXMLElement($xmlstr);

echo $xml->foo . "<br>";
echo $xml->foo[0] . "<br>";
echo $xml->foo[1] . "<br>";
echo $xml->foo[1]["att"] . "<br>";

The output of this code is:


What type of object is $xml->foo and how can I create a similar
object? It can be accessed as an array (e.g. $xml->foo[1]). But
echoing it doesn't print "Array" as usual, but rather apparently calls
the __toString method of $xml->foo[0].

Thanks a lot.


Re: how to use object as array like in simplexml wrote:
Quoted text here. Click to load it

You can add this support to your own class by implementing the
ArrayAccess interface.  See

The documentation is pretty poor, but it works something like this - you
implement each of the methods in the interface so that they do the
proper thing according to your access scheme.  Here's a simple example
that just maps object array-style access to an internal array in the object:

class ArrayAccessExample implements ArrayAccess
    private $internal = array();

    public function offsetExists($offset)
        // return true if the offset exists,
        // false otherwise
        return isset($this->internal[$offset]);

    public function offsetGet($offset)
        //return the specified offset
        //what happens if it doesn't exist is
        //up to you (return null, throw exception, etc)

            throw new Exception(
                "Index not defined"

        return $this->internal[$offset];

    public function offsetSet($offset, $value)
        //set data at specified offset
        $this->internal[$offset] = $value;

        //not sure if you have to do this
        //(as in C++ operator overloading) but it doesn't hurt
        return $value;

    public function offsetUnset($offset)
        //unset given offset so that it no longer exists

$obj = new ArrayAccessExample;
$obj[0] = "test";
$obj['foo'] = "bar";


Hope that's helpful,


Re: how to use object as array like in simplexml

Quoted text here. Click to load it

Thank you, that's exactly what I was looking for.

Site Timeline