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:
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());
}
}
Post a Comment