Recursively check trait hierarchy

Since traits can use other traits, the following function will recursively check if a class uses a trait anywhere in the trait hierarchy.

function class_uses_recursive( $class, $trait )
{
    $traits = class_uses( $class );
    
    while( !empty( $traits ))
    {
        foreach( $traits as $k => $t )
        {
            if( $t === $trait )
                return true;
            
            if( class_uses_recursive( $t, $trait ))
                return true;
            
            unset( $traits[ $k ] );
        }
    }
    
    return false;
}
Example usage
trait MyTrait1
{

}

trait MyTrait2
{
     use MyTrait1;
}

class MyClass
{
     use MyTrait2;
}

class_uses_recursive( 'MyClass', 'MyTrait1' ); // RETURNS TRUE
Happy coding

PHP 5.4 Prototype-based Programming v.2

PHP 5.4 is here and that means it’s time to use and abuse traits. This article is a follow-up to my last article on prototype-like functionality in PHP 5.4. Like before, this article is intended for advanced PHP users. After my previous article, user emehrkay on r/php very astutely pointed out that my implementation was inadequate as a prototype. In languages like Javascript, it is possible to prototype every instance of a class. In contrast, my previous implementation only applied to a single object. For example..

class MyClass
{
    use Prototype;
}

$obj = new MyClass;
$obj->hello = function()
{
    echo 'world';
};

$obj2 = new MyClass;

$obj->hello() // WORKS
$obj2->hello() // DOES NOT WORK
In order for PHP to be truly prototypal, it must be possible to easily apply an anonymous function to every instance of an object. With the latest implementation of my prototype trait, the following code is valid..

$obj = new MyClass;
$obj->hello = function()
{
    echo 'world';
};

$obj2 = new MyClass;

$obj->hello() // WORKS
$obj2->hello() // WORKS
It also works for subclasses too!

class OtherClass extends MyClass
{
    
}

$obj = new MyClass;
$obj->hello = function()
{
    echo 'world';
};

$obj2 = new OtherClass;

$obj->hello() // WORKS
$obj2->hello() // WORKS
Without further ado, here is the trait.

trait Prototype
{
    private $_props = [];
    protected static $_methods = [];
    
    function &__get( $name )
    {
        if( array_key_exists( $name, $this->_props ))
        {
            return $this->_props[$name];
        }
        
        return null;
    }
    
    function __set( $name, $value )
    {
        if( $value instanceof \Closure )
        {
            if( !array_key_exists( __CLASS__, self::$_methods ))
            {
                self::$_methods[ __CLASS__ ] = [];
            }
            
            self::$_methods[ __CLASS__ ][ $name ] = $value;
        }
        else
        {
            $this->_props[ $name ] = $value;
        }
    }
    
    function __call( $name, $args = array() )
    {
        if( array_key_exists( __CLASS__, self::$_methods ))
        {            
            $methods = self::$_methods[ __CLASS__ ];
            
            if( array_key_exists( $name, $methods ))
            {
                $method = $methods[$name];
                
                if( $method instanceof \Closure )
                {
                    $method = $method->bindTo( $this );
                }
            
                return call_user_func_array( $method, $args );
            }
        }
        
        return null;
    }
}

PHP 5.4 Traits, Closures, and Prototype-based Programming

I am really excited about the upcoming release and new features of PHP 5.4. I will not be covering the basics of traits or anonymous functions as they are both fairly well documented already. This article is intended for advanced PHP users, but if you have any questions please feel free to contact me or leave a comment.

According to Wikipedia, prototype-based programming is “a style of object-oriented programming in which classes are not present, and behavior reuse (known as inheritance in class-based languages) is performed via a process of cloning existing objects that serve as prototypes

With magic methods, traits, and anonymous functions - this is now possible in PHP. How, you ask? Consider the following code example..

    class SimpleXML
    {
        use \Prototype;
    }

    $SimpleXML = new SimpleXML();
    $SimpleXML->load = function( $path )
    {
        if( file_exists( $path ))
            return simplexml_load_file( $path );

        return null;
    };

    $SimpleXML->load = function( $data )
    {
        return simplexml_load_string( $data );
    };
The previous code uses SimpleXML and contains a class declaration by that name with a single trait that is shown later. The class is then instantiated and 2 anonymous functions are added to the prototype. With the above code and the Prototype trait, the following statements are both possible.


    $doc = $SimpleXML->load( 'test.xml' );
    $doc = $SimpleXML->load( '<test><attr>test</attr></test>' );
The first method triggers the Closure that uses simplexml_load_file and the second method triggers simplexml_load_string respectively. You may notice that both functions are assigned to the same property. Using the prototype trait, it is possible to define 2 functions with the same name and number of arguments. This is a lot like traditional method overloading which was previously not possible with PHP. Overloading in this way is primitive and requires that overloaded methods meet certain criteria, namely that a given method return null if the input is not valid.

Now for the trait..
trait Prototype
{
    private 
            $_props = array(),
            $_methods = array();

    function &__get( $name )
    {
        if( array_key_exists( $name, $this->_props ))
        {
            return $this->_props[$name];
        }
        elseif( array_key_exists( $name, $this->_methods ))
        {
            return $this->_methods[$name];
        }
        
        return null;
    }
    
    function __set( $name, $value )
    {
        if( is_object( $value ) && is_callable( $value ))
        {
            if( !array_key_exists( $name, $this->_methods ))
            {
                $this->_methods[ $name ] = array();
            }
            
            if( $value instanceof \Closure )
            {
                $value = $value->bindTo( $this );
            }
            
            $this->_methods[ $name ][] = $value;
        }
        else
        {
            $this->_props[ $name ] = $value;
        }
    }
    
    function __call( $name, $args = array() )
    {
        if( array_key_exists( $name, $this->_methods ))
        {            
            $methods = $this->_methods[ $name ];
            
            if( is_array( $methods ))
            {
                foreach( $methods as $method )
                {             
                    if( !is_null( $result = call_user_func_array( $method, $args ) ) )
                    {
                        return $result;
                    }
                }
            }
        }
        
        return null;
    }
}
The __get method
This one is fairly self-explanatory as it simply returns a property value or a Closure stored in _props and _methods respectively.

The __set method
This method first checks to see if the value is in-fact callable. An example of a callable value would be an anonymous function or a class that implements the __invoke method. If the value is a Closure, the BindTo method is called. BindTo simply allows the use of the $this keyword in the closure as you would use it in a normal method. Finally, if the value is not callable, the prototype assumes it is a property and assigns it to the _props array.

The __call method
This method iterates through all of the matching methods until one returns something other than null.

Now the prototype above is well, a prototype. As per the original definition of prototype-based programming, it must also be possible to easily extend your prototype by cloning all of it’s methods and properties. I haven’t done that for the sake of this example but such a thing would not be difficult by simply copying _props and _methods into a new prototype and triggering the aforementioned BindTo method on the copied anonymous functions.

Happy coding!

Software architecture is a cruel mistress

What is the proper way to engineer software? How much time should you spend on architecture design before building the user-facing application?

These are very simple questions, but neither have simple answers. There are many developers who like to weigh in on the issue, each offering their own, often biased, perspective.

These questions are virtually impossible to answer generally, as context is incredibly important in determining design direction. Languages and platforms tend to diverge heavily, each with individual approaches. As such, it is difficult to answer these questions without being overly ambiguous. To establish some context, we must ask another question.

How do most programmers build software?

Without a doubt, the predominant philosophy among programmers is to take shortcuts and ship the product as soon as possible. Typically the goal is to ship, make the big bucks now, and worry about refactoring design mistakes later. While this may be appealing to managers who like it quick and cheap, it doesn’t exactly create long-term or maintainable software.

In-fact, just the opposite.

In the first phases of the development life-cycle, code tends to be very malleable and subject to considerable change. It’s okay to make even drastic changes during this time because the solution has yet to be deployed. This is the best time to properly engineer software. Why?

Things get a lot harder after deployment.

After deploying a project, any further changes must be tested against legacy code. Fixing bugs and implementing new features is more tedious when constrained by backwards-compatibility. As more versions are deployed and features tacked on, a system will typically become resistant to change, therein making drastic or substantial refactoring of code a perilous task(akin to spelunking). Bad architecture simply compounds these issues, making the code all the more difficult to grapple with after-the-fact.

To put it simply, take more time in the beginning to write better code and spare yourself time-consuming headaches later on.

Happy coding!

Dijkstra’s Algorithm

There is no better explanation than that found at Wikipedia..
“Dijkstra’s algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path problem for a graph with nonnegative edge path costs, producing a shortest path tree. This algorithm is often used in routing.”

illustration

Further illustration and examples in other languages may be found at AlgoList.

Below is a PHP implementation of the algorithm.

function dijkstra( array $g, $start, $end = null )
{
    $d = array();
    $p = array();
    $q = array( 0 => $start );
    
    foreach( $q as $v )
    {
        $d[$v] = $q[$v];
        if( $v == $end )
            break;
        
        foreach( $g[$v] as $w )
        {
            $vw = $d[$v] + $g[$v][$w];
            
            if( in_array( $w, $d ))
            {
                if( $vw < $d[$w])
                    throw new Exception('Dijkstra: found better path to already-final vertex');
            }
            elseif( $vw < $q[$w] )
            {
                $q[$w] = $vw;
                $p[$w] = $v;
            }
        }
        
        return array( $d, $p );
    }
}

function shortestPath( array $g, $start, $end )
{
    list( $d, $p ) = dijkstra( $g, $start, $end );
    $path = array();
    while( true )
    {
        $path[] = $end;
        if( $end == $start ) break;
        $end = $p[$end];
    }
    
    array_reverse( $path );
    
    return $path;
}

Happy coding!

Using __invoke() to implement a delegate

A delegate is a data structure which stores a callback. Unfortunately PHP does not provide any native delegation, instead relying on the use of arrays and notoriously slow functions like call_user_func() to handle dynamic callbacks. For example:

call_user_func('MyClass::staticFunction');
In my previous article about magic methods, I gleaned a sane implementation of dynamic method overloading but neglected to mention __invoke(). The __invoke() method is a new addition to PHP 5.3 that is called when an object is used as a function.

Implementation

class MyObjectFunction
{
    function __invoke()
    {
        return 'hello world!';
    }
}
Example Usage

$myFunc = new MyObjectFunction();
echo $myFunc();
Output

hello world!
The delegate class demonstrated below is instantiated by providing class or object and a corresponding method to execute later with __invoke(). Keep in mind that this implementation is a proof-of-concept and therefore lacks any error-catching.

$myDelegate = new Delegate('MyClass','HelloWorld');
$myDelegate();
Given a proper “MyClass” implementation, the delegate’s __invoke() method will generate, validate and execute the callback provided in the constructor. In order to begin the delegate implementation, the delegate class requires at least the two properties specified below.

class Delegate
{
    public $Method;
    public $Target;

    function __construct( $target, $method = null )
    {
        $this->Target = $target;
        $this->Method = $method;
    }
}
The target argument may be a string or an object. A method may or may not be provided depending on whether or not the target is an object that implements the __invoke() method itself.

For convenience’s sake, the following methods determine if the target is static or an object. These methods are used later to generate a callback.

    function isStatic()
    {
        return is_string( $this->Target );
    }

    function isObject()
    {
        return is_object( $this->Target );
    }
In such a case that the delegate must rely on call_user_func_array(), the following function will generate a proper callback.

    function toCallback()
    {
        if( is_string( $this->Method ))
            if( $this->isStatic() )
                return $this->Target.'::'.$this->Target;
            else
                return array( $this->Target, $this->Method );

        return $this->Target;
    }
The previous method also allows the delegate to ensure that the callback is in-fact valid. For that reason, the following method will validate the callback using the is_callable() function.

    function callable()
    {
        return is_callable( $this->toCallback() );
    }
With the preliminary code provided above, the guts are now in order. After validating the callback, __invoke() relies on four methods to handle execution, namely invoke(), invokeStatic(), invokeObject(), and invokeCallback().

The first three simply handle dynamic method resolution for up to four arguments. Using dynamic resolution is not necessary, but as stated previously, call_user_func_array() is notoriously slow and therefore must be avoided(within reason). The last function, invokeCallback(), simply returns the result of call_user_func_array() as a last resort when more than four arguments are present.

    function __invoke()
    {
        if( !$this->callable() )
            return null;

        $arguments = func_get_args();

        if( $this->isStatic() )
            return $this->invokeStatic( $this->Method, $arguments );
        elseif( $this->isObject() )
            if( is_null( $this->Method ))
                $this->invokeObject( $arguments );

        return $this->invoke( $this->Method, $arguments );
    }

    private function invoke( $method, array $arguments )
    {
        $target = $this->Target;

        switch( count( $arguments ))
        {
            case 0:
                return $target->$method();
            case 1:
                return $target->$method( $arguments[0] );
            case 2:
                return $target->$method( $arguments[0],
                                         $arguments[1] );
            case 3:
                return $target->$method( $arguments[0],
                                         $arguments[1],
                                         $arguments[2] );
            case 4:
                return $target->$method( $arguments[0],
                                         $arguments[1],
                                         $arguments[2],
                                         $arguments[3] );
        }

        return $this->invokeCallback( $arguments );
    }

    private function invokeObject( array $arguments )
    {
        $target = $this->Target;

        switch( count( $arguments ))
        {
            case 0:
                return $target();
            case 1:
                return $target( $arguments[0] );
            case 2:
                return $target( $arguments[0],
                                $arguments[1] );
            case 3:
                return $target( $arguments[0],
                                $arguments[1],
                                $arguments[2] );
            case 4:
                return $target( $arguments[0],
                                $arguments[1],
                                $arguments[2],
                                $arguments[3] );
        }

        return $this->invokeCallback( $arguments );
    }

    private function invokeStatic( $method, array $arguments )
    {
        $target = $this->Target;

        switch( count( $arguments ))
        {
            case 0:
                return $target::$method();
            case 1:
                return $target::$method( $arguments[0] );
            case 2:
                return $target::$method( $arguments[0],
                                         $arguments[1] );
            case 3:
                return $target::$method( $arguments[0],
                                         $arguments[1],
                                         $arguments[2] );
            case 4:
                return $target::$method( $arguments[0],
                                         $arguments[1],
                                         $arguments[2],
                                         $arguments[3] );
        }

        return $this->invokeCallback( $arguments );
    }

    function invokeCallback( array $arguments )
    {
        return call_user_func_array( $this->toCallback(), $arguments );
    }

Happy coding!

Kinesis is a framework that uses the latest techniques available in PHP 5.3. Completely object-oriented, Kinesis is heavily divergent from the messy procedural non-sense so common to PHP frameworks.

(Source: github.com)

Dynamic property & method overloading using magic methods

The __get(), __set(), __isset(), __unset(), __call(), and __callStatic() magic methods provide a means to dynamically access properties and methods of an object. Said methods invoke automatically when using conventional accessor, mutator, and function syntax. With the exception of __callStatic(), all of these methods may only exist in an object’s context or local scope. Conversely, the __callStatic() method is defined as static and therefore accessed with the scope resolution operator, or paamayim nekudotayim(i.e. double colon).

This functionality is typically used as a fallback in case a requested property or method is not explicitly defined. Additionally, methods or properties that are inaccessible because they are defined private or protected will also invoke magic methods from a global scope. This is useful if an object needs to provide conditional access to a hidden property. For example, in the case of accessing a password property on a user object, said object may require an authenticator to ensure access is only possible under certain circumstances.

Property overloading

__set ( string $name , mixed $value )
Invoked when mutating a specified key-pair
__get ( string $name )
Retrieves the matching key value
__isset ( string $name )
Determines if a key-pair exists.  
Only invoked as the subject of either the isset() or empty() calls.
__unset ( string $name )
Destroys a key-pair in memory so the memory can be re-allocated.  
Only invoked as the subject of an unset() call.
The Object class below implements a constructor which accepts an array argument and assigns it to a private property. Then the array values are exposed dynamically with the magic methods mentioned earlier, __get, __set, __isset, and __unset respectively.

class Object
{
    // local consolidated property array
    protected $property = array();

    function __construct( array $property = null )
    {
        if( is_array( $property ) )
            $this->property = $property;
    }

    function __get( $name )
    {
        return $this->property[ $name ];
    }

    function __set( $name, $value )
    {
        $this->property[ $name ] = $value;
    }

    function __isset( $name )
    {
        return array_key_exists( $name, $this->property );
    }

    function  __unset( $name )
    {
        unset( $this->property[ $name ] );
    }
}
Example usage
// create array with default properties
$property = array( 'myprop' => 'someValue', 
                   'myfield' => 2 );

// instantiate object, passing default property array into constructor
$object = new Object( $property );

// magic methods
// test __get procedure
echo $object->myprop;

// test __set procedure
$object->myprop = 'newValue';
echo $object->myprop;

// test __isset procedure
if( isset( $object->myprop ) )
    echo 'myprop exists!';

// test __unset procedure
unset( $object->myprop )
var_dump( $object->myprop );

Output
someValue
newValue
myprop exists!
null
Method overloading
Much like property overloading, to overload a method means to implement magic methods such as __call or __callStatic. Both accept a method name and an array of parameters as arguments. A typical implementation just identifies and invokes an appropriate fallback function.

__call ( string $name , array $arguments )
Invoked when attempting to call a local method that is inaccessible
__callStatic ( string $name , array $arguments )
Invoked when attempting to call a static method that is inaccessible
The following class is a simple example of how the __call() method can expose otherwise private methods globally.

class Object
{
    private function Output()
    {
        echo __METHOD__ . ' successful!';
    }

    function __call( $methodName, $arguments )
    {
        echo 'Invoking __call(' . $methodName . ')';
        if( method_exists( $this, $methodName ))
            return $this->$methodName();

        return null;
    }
}
Example usage
$object = new Object();

$object->Output();
Output
Invoking __call(Output)
Output successful!
This example demonstrates that an inaccessible method may be exposed through __call() magic. It is important to note that exposing otherwise hidden methods may pose a security risk and as such is only used for testing purposes.

The previous implementation uses dynamic variable resolution to determine the method to invoke. Typically this performs better than the common alternative, call_user_func() shown below.
    function __call( $methodName, $arguments )
    {
        if( method_exists( $this, $methodName ))
            return call_user_func( array( $this, $methodName ) );

        return null;
    }
Despite performance limitations, sometimes it may be necessary to invoke methods using call_user_func_array() instead, since it behaves similarly to call_user_func() and accepts a parameter array that is passed into the callback’s arguments. Therein avoiding the necessity to modify the callback function to accept a parameter array like that passed into __call().
    function __call( $methodName, $arguments )
    {
        if( method_exists( $this, $methodName ))
            return call_user_func_array( array( $this, $methodName ), $arguments );

        return null;
    }
Because of performance issues, some developers choose to hard-code method resolution up to a certain number of arguments, using call_user_func_array() only as a last resort.
function __call( $methodName, $arguments )
{
    switch( count( $arguments ))
    {
        case 0:
            return $this->$methodName();
        case 1:
            return $this->$methodName( $arguments[0] );
        case 2:
            return $this->$methodName( $arguments[0],
                                       $arguments[1] );
        case 3:
            return $this->$methodName( $arguments[0],
                                       $arguments[1],
                                       $arguments[2] );
        case 4:
            return $this->$methodName( $arguments[0],
                                       $arguments[1],
                                       $arguments[2],
                                       $arguments[3] );
        default:
            return call_user_func_array( array( $this, $methodName ), $arguments );
        break;
    }
}
The previous method is anything but elegant, despite being considerably faster for methods with less than 5 arguments. Upon reviewing this code, a seasoned developer may immediately want to implement it using dynamically generated code and eval() for execution. However, using eval() is generally frowned upon because it performs even worse than call_user_func_array() and lacks support on many platforms.

The example shown below is equivalent to the previous example except that it uses the __callStatic() method instead of __call().

class Object
{
    private static function Output()
    {
        echo 'Static output successful!';
    }

    static function __callStatic( $methodName, $arguments )
    {
        switch( count( $arguments ))
        {
            case 0:
                return self::$methodName();
            case 1:
                return self::$methodName( $arguments[0] );
            case 2:
                return self::$methodName( $arguments[0],
                                          $arguments[1] );
            case 3:
                return self::$methodName( $arguments[0],
                                          $arguments[1],
                                          $arguments[2] );
            case 4:
                return self::$methodName( $arguments[0],
                                          $arguments[1],
                                          $arguments[2],
                                          $arguments[3] );
            default:
                return call_user_func_array( __CLASSNAME__'::'.$methodName , $arguments );
            break;
        }
    }
}
Example usage
Object::Output();
Output
Invoking __callStatic(Output)
Static output successful!
Happy coding

Array overloading with ArrayAccess & Countable interfaces

With the advent of the SPL, PHP now provides an easy way to use objects as arrays, thereby enabling the implementation of custom array behavior using conventional array syntax. This functionality is available through the ArrayAccess interface. Furthermore, other array behavior, such as the count() function, is available by implementing the Countable interface.

ArrayAccess Interface
It is important to note that, while custom array implementations allow considerable flexibility, they typically perform much worse than native arrays. Therefore it is advisable only to implement the ArrayAccess interface when performance is not a system requirement. Typically an array object will perform on average 4x worse than a native array(though benchmarks tend to vary drastically depending on platform).

interface ArrayAccess 
{
    abstract public boolean offsetExists ( mixed $offset )
    abstract public mixed offsetGet ( mixed $offset )
    abstract public void offsetSet ( mixed $offset , mixed $value )
    abstract public void offsetUnset ( mixed $offset )
}
The following class simply accepts an array of attributes as a constructor argument and exposes said array through the ArrayAccess methods. This implementation is very similar to one I use myself for tree nodes.
class MyTreeNode implements ArrayAccess, Countable
{
    protected $attributes;
    protected $parent;
    
    function __construct( array $attributes, MyTreeNode $parent = null )
    {
        $this->attributes = $attributes;
        $this->parent = $parent;
    }
    
    function getParent()
    {
        return $this->parent;
    }
    
    public function offsetExists ( $offset )
    {
        return array_key_exists( $offset, $this->attributes );
    }
    
    public function offsetGet ( $offset )
    {
        return $this->attributes[ $offset ];
    }
    
    public function offsetSet ( $offset , $value )
    {
        $this->attributes[ $offset ] = $value;
    }
    
    public function offsetUnset ( $offset )
    {
        unset( $this->attributes[ $offset ] );
    }

    public function count()
    {
        return count( $this->attributes );
    }
}
Example usage
$attributes = array( 'myAttr' => 'someValue', 
                     'myAttr2' => 2 );

$node = new MyTreeNode( $attributes );

echo $node['myAttr'];
Output
someValue
Example looping
foreach( $node as $attr => $value )
{
    echo $attr . ': ' . $value;
}
Output
myAttr: someValue
myAttr2: 2
Countable Interface
Arrays themselves have a finite length, and therefore must implement the Countable interface in order for the count() function to be used on them.
interface Countable
{
    abstract public int count ( void )
}
Example using the previous MyTreeNode class
echo count( $node );
Output
2

Loop overloading with Traversable, Iterator, & IteratorAggregate interfaces

These 3 interfaces are designed to overload default foreach looping behavior. Conventional iteration overloading is possible using the Traversable interface via the Iterator and IteratorAggregate interfaces. Furthermore, custom filtering, searching, comparisons, and integration are also possible with a custom Iterator.



Other Iterator Interfaces
Additional functionality may be implemented through the many other iterators provided by the SPL, such as the OuterIterator, RecursiveIterator, ArrayIterator, LimitIterator, FilterIterator, RegexIterator, and CachingIterator just to name a few.

Traversable Interface
Attempting to implement the Traversable interface directly will result in an error since it’s only meant to be used internally. Only descendants of Traversable such as the Iterator and IteratorAggregate interfaces can instead be used

IteratorAggregate Interface
This interface simply allows object iteration without requiring a full Iterator implementation in the object itself. By defining the getIterator() method from the IteratorAggregate interface, a class can offload the iteration procedure to a proper Iterator, like the ArrayIterator in the following example.

class Iterable implements IteratorAggregate
{
    protected $array;

    function __construct( array $array = null )
    {
         if( is_array( $array ) )
             $this->setArray( $array );
    }

    function getArray()
    {
         return $this->array;
    }

    function setArray( array $array )
    {
         $this->array = $array;
    }

    function getIterator()
    {
         return new ArrayIterator( $this->array );
    }
}
Example usage
$array = array( 1, 2, 3, 4 );

$iterable = new Iterable( $array );

foreach( $iterable as $item )
{
    echo $item;
    echo "\n";
}
Output
1
2
3
4
Iterator Interface
An iterator is essentially a class that may be used in a looping structure and that may also provide advanced data-access methods. An iterator’s required methods as defined by the Iterator interface are current(), key(), next(), rewind(), and valid(). In order to be easily overloaded, the following iterator implements these methods using common array-access methods. Furthermore, the following implementation works regardless of the type of key used in the array.
class MyIterator implements Iterator
{
    protected $values;

    protected $keys;

    private $_position = 0;


    function __construct( array $array = null )
    {
        if( is_array( $array ))
            $this->setArray( $array );
    }

    function next()
    {
        $this->increment();

        return $this->current();
    }

    function valid()
    {
        if( array_key_exists( $this->_position, $this->values ))
            return true;

        return false;
    }

    function rewind()
    {
        $this->_position = 0;
    }

    function current()
    {
        return $this->values[ $this->_position ];
    }

    function key()
    {
        return $this->keys[ $this->_position ];
    }

    function clear()
    {
        $this->values = array();
        $this->keys = array();
    }

    function setArray( array $array )
    {
        $this->values = array_values( $array );
        $this->keys = array_keys( $array );
    }
    
    function getArray()
    {
        return array_combine( $this->keys, $this->values );
    }

    protected function increment()
    {
        ++$this->_position;
    }

    protected function decrement()
    {
        --$this->_position;
    }

    protected function position()
    {
        return $this->_position;
    }
}
Example usage
$iterator = new MyIterator( array( 'item1' => 1, 
                                              2, 
                                   'item3' => 3, 
                                              4 ) );

foreach( $iterator as $key => $item )
{
    echo $key . ': ' . $item;
    echo "\n";
}
Output
item1: 1
: 2
item3: 3
: 4