I’m looking for a solution on how to use argument list for instantiating class’ dynamically.
For example:
class test {
public function __call($name, $args){
/* blah, blah class exists? require */
return new $name($args);
}
public function __toString(){
return (string) $this->extension(); // to enforce __toString of extension
}
}
class extension extends test {
public function __construct(classTypeHint $object, $required, $random = 25){
// This does not work, results in:
// "Argument 1 passed to extension::__construct must be an instance of classTypeHint, array given...
}
public function __toString(){
return var_export($this, true);
}
}
echo new test;
As comment states, that results in error, but I’m looking to be able to access $object as ($args[0]), $required as ($args[1]) etc. Plus, enforce "correct" arguments.
Why am I looking for this?
The __autoload functionality of PHP is limited. Well, maybe it’s not, but I have not found an easy way to differentiate class autoloads.
With this functionality, I can use __call(), __get(), __callStatic() for three different autoloads. Like:
__call()looks for libraries in/includes/libraries__get()looks for plugins in/application/plugins__callStatic()looks for, umm, cats in/application/cats
If there is a better way through autoloading, please share. But I’m still looking for such a solution, if it’s possible. Maybe with Reflection classes?
Somewhat working example with ReflectionClass:
$instance = new ReflectionClass($name);
$instance->newInstanceArgs($arguments);
return $instance;
But it’s obvious here, that it will call ReflectionClass->__toString() here. Plus, overlooking the returned dump, it actually does not use the newInstanceArgs() here.
Notes:
I’m interested in example working prior to PHP 5.3.
Use reflection:
it takes an array just like
call_user_func_arrayEdit: a working example: http://codepad.org/ZZpBwRij