Search code examples
phpanonymous-functionphp-5.2

Closure objects within arrays before PHP 5.3


I know it's possible to do the following with PHP 5.3 (anonymous functions), but is there a similar alternative in older PHP version (pre-5.3)?

  $exampleArray = array(  
    'func' => function() {  
      echo 'this is an example';  
      }

Is it possible to do this with __call or typecasting the function as an (object) first? Also, I tried making the function un-anonymous by giving it a name, but this didn't seem to work.


Solution

  • If you want to create anonymous in PHP < 5.3, you can use create_function function. Also Here is interesting information about callbacks (may be usefull).

    Example using create_function

    # This (function in other variable is only for cleaner code)
    $func = create_function('', "echo 'This is example from anoymus function';");
    
    $exampleArray = array(
      'func' => $func
      );
    

    But you can do the same thing liek code above with alternative way:

    # Create some function
    function func()
    {
       # Do something
       echo 'This is example';
    }
    # Save function name
    $func = 'func';
    

    Code above creates function which does something, then we store function name in variable (can be passed as parameter, etc.).

    Calling function when we know only it's name:

    First way

    $func();
    

    Alternative

    call_user_func($func);
    

    So example that connects everything above:

    function primitiveArrayStep(&$array, $function)
    {
        # For loop, foreach can also be used here
        for($i = 0; $i < count($array);$i++)
        {
             # Check if $function is callable             
              if( is_callable($function) )
              {
                   # Call function
               $function(&$array[$i]);
              }
              else
              {
                   # If not, do something here
              }
    
        }    
    }
    

    And use of above function:

    $array = array('a', 'b', 'c');
    
    $myFunction = create_function('&$e', '$e = $e . " and i was here";');
    
    primitiveArrayStep($array, $myFunction);
    
    echo '<pre>';
    var_dump($array);
    

    Returns:

    array(3) {
      [0]=>
      string(16) "a and i was here"
      [1]=>
      string(16) "b and i was here"
      [2]=>
      string(16) "c and i was here"
    }
    

    Links: