Reputation: 3596
$app = 'App here';
$fn1 = function($var) use($app){
$fn2($var);
};
$fn2 = function($var) use($app){
echo $var;
};
$fn1('variable');
In the above example, I am trying to chain/forward multiple anonymous functions. However, at the below line I receive an error "Notice: Undefined variable: fn2"
$fn2($var)
How do I achieve the chaining of anonymous functions.
Upvotes: 2
Views: 606
Reputation: 11942
Just to clarify a few things first, chaining is something traditionally attributed to the Object Oriented Paradigm (as in method chaining), whereby one method returns an instance in order to chain multiple method calls together on the return value of each successive method.
In a functional paradigm what you're doing is more commonly referred to as a higher order function - or a function whose argument takes another function or returns a function.
The problem with your existing code is that functions in PHP do not implicitly import variables from the global scope (see variable scoping in PHP) or any other block scope. The only caveat being that they do gain access to $this
or the object instance when they are defined within object context (i.e. inside of a class method that is not static). At least as of PHP 5.4.
So instead you must explicitly import variables from the global or local scope outside of the closure by using the use
statement, which you have used to import the variable $app
in your example. Though, importing variables touching the outer scope may not always be an elegant solution within a functional paradigm, assuming that is what you're going for.
So in the essence of a higher order function you can more succinctly express your code in the following manner...
$app = 'App here';
$fn1 = function($fn2, $var) use($app){
$fn2($var);
};
$fn2 = function($var) use($app){
echo $var;
};
$fn1($fn2, 'variable');
Which would give you the output variable
.
Upvotes: 3
Reputation: 184
You need to define $fn2
before you use the variable
EDIT: and to pass the variable in the use()
$app = 'App here';
$fn2 = function($var) use($app){
echo $var;
};
$fn1 = function($var) use($app, $fn2){
$fn2($var);
};
$fn1('variable');
Upvotes: 1
Reputation: 59701
The problem is, that your variable $fn2
is out of scope in your first anonymous function. So just put the assignment of $fn2
before $fn1
and then pass the variable as you already did in the use()
, e.g. $fn1 = function($var) use($app, $fn2){
Upvotes: 3
Reputation: 1102
The problem is that you are not passing the $fn2
as a parameter in the use
statement of the closure.
Try the following code:
$app = 'App here';
$fn2 = function($var) use($app){
echo $var;
};
$fn1 = function($var) use($app, $fn2){
$fn2($var);
};
$fn1('variable');
Here you have your example working in an online php tester.
Upvotes: 5