note 107949 added to functions.anonymous
| From: | orwellophile at phpblue dot net | Date: | Fri, 16 Mar 2012 04:42:47 +0000 |
| Subject: | note 107949 added to functions.anonymous | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-186700@lists.php.net to get a copy of this message | ||
You can create a dynamic method with a class, with access to member variables, with a little bit of
trickery:
<?
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");
};
?>
----
Server IP: 69.147.83.197
Probable Submitter: 111.223.237.154
----
Manual Page -- http://www.php.net/manual/en/functions.anonymous.php
Edit -- https://master.php.net/note/edit/107949
Del: integrated -- https://master.php.net/note/delete/107949/integrated
Del: useless -- https://master.php.net/note/delete/107949/useless
Del: bad code -- https://master.php.net/note/delete/107949/bad+code
Del: spam -- https://master.php.net/note/delete/107949/spam
Del: non-english -- https://master.php.net/note/delete/107949/non-english
Del: in docs -- https://master.php.net/note/delete/107949/in+docs
Del: other reasons-- https://master.php.net/note/delete/107949
Reject -- https://master.php.net/note/reject/107949
Search -- https://master.php.net/manage/user-notes.php