- URL: https://www.laruence.com/en/2010/06/20/1602.html
- Please include attribution when republishing.
In PHP, the way we pass callbacks around has always been ugly. Before PHP 5.3, we had only two choices:
1. A function name as a string 2. The return value of create_function
After PHP 5.3, we got one more choice, namely Closure,
$func = function () { ... };
array_walk($arr, $func);
In terms of implementation, the first approach — passing a function name string — is the simplest.
The second approach, create_function, is essentially the same as the first: create_function returns a function name as a string, and that name has the format:
"\000_lambda_" . count(anonymous_functions)++;
Let's look at the implementation steps of create_function:
1. Fetch the arguments and the function body
2. Assemble a string of the form "function __lambda_func (args) { body;}"
3. eval it
4. Find the function body produced by eval in the function table via __lambda_func; raise an error if not found
5. Define a function name: "