Friday, January 28, 2011

Flatr - Example of references inside Closures in PHP

Last post I wrote a small example showing how to use Closures in PHP, the recursive way. Today I'll show you how to use a paramater passed by reference to convert a complex object structure in a flat array, with elegance and simplicity.

Without delay here's the Flatr function:

// Example structure
$obj = new stdClass();
$obj->prop1 = 'hello';
$obj->prop2 = new stdClass();
$obj->prop2->prop2 = 'there';
$obj->prop2->prop3 = 'world!';
/**
 *
 * @param stdClass $obj
 * @return array
 */
function flatr($obj) {
    $ret = array();

    $recursiveWalk = function( $baseObject ) use (&$recursiveWalk, &$ret) {
        if (is_object($baseObject)) {
            foreach($baseObject as $propValue) $recursiveWalk($propValue);
        } else {
            $ret[] = $baseObject;
        }
    };
    $recursiveWalk($obj);

    return $ret;
}
var_dump(flatr($obj));


This will output:

array(3) { [0]=> string(5) "hello" [1]=> string(5) "there" [2]=> string(6) "world!" }

This little function is not ready to handle arrays inside the object structure. But the required changes are not hard to make.

Next post I'll demonstrate a practical usage for this function.

No comments: