Thursday, September 23, 2010

instantiating object inline via __callStatic

This is a nice hack for instantiating objects inline via php 5.3 __callStatic. What I dig about it v.s. the newObject('ClassName') is that a) You can pass in arbitrary constructors, w/ newObject it only supported the case of there being a single param to constructor i.e. newObject('ClassName', $x)->otherFunc($y) can now be N::ClassName($x)->otherFunc($y). I think I like the fact the class can be a "bare word" and that any number of constructors can be passed thus legacy classes etc. which may require arbitrary arguments can also be used.


class Test {
public function __construct($name, $age)
{
echo "Name: $name and Age: $age passed to constructor\n";
}
}

class N {
public static function __callStatic($className, $args)
{
$class = new ReflectionClass($className);
return $class->newInstanceArgs($args);
}
}

N::Test('some name', 300);

No comments: