/Main_Page

::You must have ninja focus to complete your mission::NinjaFocus::

PHP ArrayAccess Object

Views:

A class that will let your objects behave like an array (almost). There is no automatic incrementing of the index, so no $myArray[] = 'foo'. However you can create a data graph with this class.

<?php
/**
 * @package ninja
 * @copyright Kieran Whitbread 2006-2010
 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
 */
/**
 * A class that will let your objects behave like an array (almost)
 * 
 * there is no automatic incrementing of the index, so no $myArray[] = 'foo'.
 *
 * However you can create a data graph with this class.
 *
 * @package ninja
 * @author Kieran Whitbread
 **/
class NinjaArrayAccessObject implements ArrayAccess, Countable
{
    /**
     * Pass in a name value pair, or just an array, or another NinjaArrayAccessObject
     * to populate the data in the new object.
     *
     * @return void
     * @author Kieran Whitbread
     **/
    public function __construct($name = null, $value = null)
    {
        if (!is_null($name))
        {
            $this->set($name, $value);
        }
    }
	public function offsetExists($offset)
	{
		return in_array($offset, array_keys(get_object_vars($this)));
	}
	public function offsetGet($offset)
	{
		return $this->$offset;
	}
	public function offsetSet($offset, $value)
	{
		$this->set($offset, $value);
	}
	public function offsetUnset($offset)
	{
		unset($this->$offset);
	}
	public function count()
	{
	    return count(get_object_vars($this));
	}
	/**
     * Bulk addition and type conversion of data to be added to a template
     *
     * @param mixed $name an array of values to set, or the name (as a string) for a corresponding value passed as the second argument
     * @param mixed $value (optional) the value to set, if a name was provided
     * @return void
     * @author Kieran Whitbread
     **/
    public function set($name, $value=null)
    {
        if (is_array($name) || $name instanceof NinjaArrayAccessObject)
        {
            foreach($name as $key => $value)
            {
                $this->set($key, $value);
            }
        }
        elseif (is_array($value))
        {
            $obj = new NinjaArrayAccessObject();
            foreach ($value as $arrKey => $arrValue)
            {
                $obj->set($arrKey, $arrValue);
            }
            $this->set($name, $obj);
        }
        else
        {
            $this->$name = $value;
        }
    }
	
}

Main Menu

Personal tools

Toolbox