How do I create a dynamic method in PHP?
I'm trying to extend my ActiveRecord class with some dynamic methods. I would like to be able to run this from my controller
$user = User::find_by_username(param);
$user = User::find_by_email(param);
I've read a little about overloading and think that's the key. I'v got a static $_attributes
in my AR class and I get the table name 开发者_StackOverflow社区by pluralizing my model (User = users) in this case.
How do I do this? All models extends the ActiveRecord class.
You have to use the __callStatic() magic method, which is available as PHP5.3
public static function __callStatic($name, $arguments) {
/*
Use strpos to see if $name begins with 'find_by'
If so, use strstr to get everything after 'find_by_'
call_user_func_array to regular find method with found part and $arguments
return result
*/
}
This might also be of use, it's more complex, but it allows true dynamic functions with access to member variables.
class DynamicFunction {
var $functionPointer;
var $mv = "The Member Variable";
function __construct() {
$this->functionPointer = function($arg) {
return sprintf("I am the default closure, argument is %s\n", $arg);
};
}
function changeFunction($functionSource) {
$functionSource = str_replace('$this', '$_this', $functionSource);
$_this = clone $this;
$f = '$this->functionPointer = function($arg) use ($_this) {' . PHP_EOL;
$f.= $functionSource . PHP_EOL . "};";
eval($f);
}
function __call($method, $args) {
if ( $this->{$method} instanceof Closure ) {
return call_user_func_array($this->{$method},$args);
} else {
throw new Exception("Invalid Function");
}
}
}
if (!empty($argc) && !strcmp(basename($argv[0]), basename(__FILE__))) {
$dfstring1 = 'return sprintf("I am dynamic function 1, argument is %s, member variables is %s\n", $arg, $this->mv);';
$dfstring2 = 'return sprintf("I am dynamic function 2, argument is %s, member variables is %s\n", $arg, $this->mv);';
$df = new DynamicFunction();
$df->changeFunction($dfstring1);
echo $df->functionPointer("Rabbit");
$df->changeFunction($dfstring2);
$df->mv = "A different var";
echo $df->functionPointer("Cow");
};
精彩评论