1

Is it possible to do something like this. Lets say we have a function that accepts string as argument. But to provide this string we have to do some processing of data. So I decided to use closures, much like in JS:

function i_accept_str($str) {
   // do something with str
}

$someOutsideScopeVar = array(1,2,3);
i_accept_str((function() {
    // do stuff with the $someOutsideScopeVar
    $result = implode(',', $someOutsideScopeVar); // this is silly example
    return $result;
})());

The idea is to when calling i_accept_str() to be able to directly supply it string result... I probably can do it with call_user_func which is known to be ineffective but are there alternatives?

Both PHP 5.3 and PHP 5.4 solutions are accepted (the above wanted behavior is tested and does not work on PHP 5.3, might work on PHP 5.4 though...).

ddinchev
  • 33,683
  • 28
  • 88
  • 133
  • The function return value dereferencing you're suggesting is not currently possible in any version of PHP. You *can* implement the `use` statement, however, to access `$someOutsideScopeVar` inside the closure and hack together the functionality with `call_user_func`. –  Feb 26 '13 at 18:18

1 Answers1

2

In PHP (>=5.3.0, tested with 5.4.6) you have to use call_user_func and import Variables from the outer Scope with use.

<?php

function i_accept_str($str) {
   // do something with str
   echo $str;
}

$someOutsideScopeVar = array(1,2,3);
i_accept_str(call_user_func(function() use ($someOutsideScopeVar) {
    // do stuff with the $someOutsideScopeVar
    $result = implode(',', $someOutsideScopeVar); // this is silly example
    return $result;
}));
pce
  • 5,571
  • 2
  • 20
  • 25