当前位置: 动力学知识库 > 问答 > 编程问答 >

can't execute function returned in variable php

问题描述:

I have a function with this syntaxe :

$variable = function() {

return function(){

//code

}

}

I can't execute that function with

$variable()

Is there a way to execute this function ?

网友答案:

I don't know for what is it... But here example:

$a = function () {
   return function () { 
       return 1; 
   };
};
$b = $a();
echo $b();
网友答案:

Your anonymous function (outer function), stored in a $variable returns another function (inner function).

Calling $variable() means that outer function returns inner one. See - returns, not executes. But as you don't assign result of outer function to any variable, your inner function is not stored anywhere.

So, the solution is:

$res = $variable();  // res stores an inner function
$res();

Or (in PHP7)

$variable()();
网友答案:

The function is returning and the calling is not doing anything with it use echo:

echo $variable();

I would suggest having separate functions instead for clarity.

$variable = doSomething();

function doeSomething(){
   //code
}
网友答案:

Without assing to new variable you can do this:

call_user_func($variable());

分享给朋友:
您可能感兴趣的文章:
随机阅读: