note 74492 added to function.create-function
| From: | kkaiser at revolution-records dot net | Date: | Fri, 13 Apr 2007 20:10:09 +0000 |
| Subject: | note 74492 added to function.create-function | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-125367@lists.php.net to get a copy of this message | ||
In the process of migrating a PHP4 codebase to PHP5, I ran into a peculiar problem. In the library,
every class was derived from a generic class called 'class_container'.
'class_container' contained an array called runtime_functions and a method called
class_function that was as follows:
function class_function($name,$params,$code) {
$this->runtime_functions[$name] = create_function($params,$code);
}
In a subclass of class_container, there was a function that utilized class_function() to store some
custom lambda functions that were self-referential:
function myfunc($name,$code) {
$this->class_function($name,'$theobj','$this=&$theobj;'.$code);
}
In PHP4, this worked just fine. The idea was to write blocks of code at the subclass level, such as
"echo $this->id;", then simply $MYOBJ->myfunc("go","echo
$this->id;"); and later call it like $MYOBJ->runtime_functions["go"]();
It essentially worked exactly like binding anonymous functions to objects in Javascript.
Note how the "$this" keyword had to be manually redefined for the $code block to work.
In PHP5, however, you can't redeclare $this without getting a fatal error, so the code had to
be updated to:
function myfunc($name,$code) {
$this->class_function($name,'$this',$code);
}
Apparently create_function() allows you to set $this via a function argument, allowing you to bind
anonymous functions to instantiated objects. Thought it might be useful to somebody.
----
Server IP: 69.147.83.197
Probable Submitter: 75.9.130.114
----
Manual Page -- http://www.php.net/manual/en/function.create-function.php
Edit -- https://master.php.net/note/edit/74492
Del: integrated -- https://master.php.net/note/delete/74492/integrated
Del: useless -- https://master.php.net/note/delete/74492/useless
Del: bad code -- https://master.php.net/note/delete/74492/bad+code
Del: spam -- https://master.php.net/note/delete/74492/spam
Del: non-english -- https://master.php.net/note/delete/74492/non-english
Del: in docs -- https://master.php.net/note/delete/74492/in+docs
Del: other reasons-- https://master.php.net/note/delete/74492
Reject -- https://master.php.net/note/reject/74492
Search -- https://master.php.net/manage/user-notes.php