All pastes #400871 Raw Edit

anon funcs in PHP

public text v1 · immutable
#400871 ·published 2007-03-18 23:29 UTC
rendered paste body
<?php

$data = array("zoo", "orange", "car", "lemon", "apple");
usort($data, function($a, $b) { return strcmp($a, $b); });
var_dump($data);

echo "\n";
?>

outputs:

array(5) {
  [0]=>
  string(5) "apple"
  [1]=>
  string(3) "car"
  [2]=>
  string(5) "lemon"
  [3]=>
  string(6) "orange"
  [4]=>
  string(3) "zoo"
}


Made possible with this patch:


diff -u -p -r1.160.2.4.2.3 zend_language_parser.y
--- zend_language_parser.y      10 Jan 2007 15:58:07 -0000      1.160.2.4.2.3
+++ zend_language_parser.y      18 Mar 2007 23:28:08 -0000
@@ -620,6 +620,29 @@ expr_without_variable:
        |       T_ARRAY '(' array_pair_list ')' { $$ = $3; }
        |       '`' encaps_list '`' { zend_do_shell_exec(&$$, &$2 TSRMLS_CC); }
        |       T_PRINT expr  { zend_do_print(&$$, &$2 TSRMLS_CC); }
+       |       T_FUNCTION {
+                       /* inline function declaration, its value is the function name */
+                       char name[64];
+                       int namelen;
+                       static unsigned int anon_count;
+                       namelen = zend_sprintf(name, "__zend_anon_%u", anon_count++);
+                       $1.u.opline_num = CG(zend_lineno);
+                       $$.op_type = IS_CONST;
+                       $$.u.constant.type = IS_STRING;
+                       $$.u.constant.value.str.val = estrdup(name);
+                       $$.u.constant.value.str.len = namelen;
+                       $$.u.constant.refcount = 1;
+               } is_reference { zend_do_begin_function_declaration(&$1, &$$, 0, $2.op_type, NULL TSRMLS_CC); }
+                       '(' parameter_list ')' '{' inner_statement_list '}' {
+
+                       $$.op_type = IS_CONST;
+                       $$.u.constant.type = IS_STRING;
+                       $$.u.constant.value.str.val = estrdup(CG(active_op_array)->function_name);
+                       $$.u.constant.value.str.len = strlen($$.u.constant.value.str.val);
+                       $$.u.constant.refcount = 1;
+                       zend_do_end_function_declaration(&$1 TSRMLS_CC);
+               }
+
 ;
 
 function_call: