Tuesday, March 2, 2010

Static Constructor in PHP :: Base Object :: Part 1

In these series I will show a few neat examples of what is possible with PHP5-5.3. I will not reiterate on the obvious, but try to expose the features that are not widely explored.

Starting from this first article I will be building a base object for our library: class Object, so that every class extending it would inherit all the features we add here.

The first feature is indirectly available to us from PHP5.0.

INLINE STATIC CONSTRUCTOR:

class Object {
    public static function construct() {
        $aArgs = func_get_args();
        $nArgCount = count($aArgs);
        $aArgTokens = array('$this');
        for ($i=0; $i<$nArgCount; $i++) {
            $aArgTokens[] = '$aArgs['.$i.']';
        }
        $sArgTokens = implode(',', $aArgTokens);
        $sEval = 'return new '.get_called_class().'('.$sArgTokens.');';
        return eval($sEval);
    }
}
What does it do? Well, consider this code:
$oMyObject = new Object();
    $oMyObject->myMethod();
You can now do:
Object::construct()->myMethod();

Notice, you can still assign the return value to $oMyObject for the future reference if needed.

Stay tuned, more interesting patters coming up.

1 comment:

Petah said...

A much better way is:

class Object {
public static function construct() {
$class = get_called_class();
$reflection_object = new \ReflectionClass($class);
return $reflection_object->newInstanceArgs(func_get_args());
}
}