Array operator overloading

ArrayAccess interface is an excellent offer from PHP. Though I do not personally like the idea of operator overloading, this interface can be a great tool for developing application faster and neatly by overloading the array access.

The interface is to be implemented by a class and override the accessors methods.

Class diagram of ArrayAccess interface

I am giving a simple code that demonstrate its usage.

 class MyArray implements ArrayAccess {        
    private $arr = array();

    function offsetExists($name) {               
        return isset($name);
    }

    function offsetGet($name) {        
        return $arr[$name];
    }

    function offsetSet($key, $val) {        
        $arr[$key]=$val;
    }

    function offsetUnset($name) {        
        unset($arr[$name]);
    }
}
$arr = new MyArray();
$userMap["Hello"]="Worlds";
echo $userMap["Hello"];

This class can use a database for its model. The interface facilitates coding array style with similar __get() __set() functionalities for classes.

Btw, anybody knows how I can show codes like code in an editor with line number ?

One Response to Array operator overloading

  1. hasin says:

    using Highlight.js or Geshi you can display codes with line numbers.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.