【问题标题】:Store the return value from an anonymous function into a variable outside its scope将匿名函数的返回值存储到其范围之外的变量中
【发布时间】:2014-04-19 22:59:02
【问题描述】:
$count = 2;
$amt = 4;
$str = function($count, $amt) {
return "There is ". $count . " and " . $amt;
};
echo $str . "!";

如何将匿名函数的返回值存储到变量中?我知道整个函数本身都存储在 $str 中,这就是为什么这不起作用,但是有办法吗?

【问题讨论】:

    标签: php closures anonymous-function


    【解决方案1】:

    您应该简单地将$str 作为函数调用:

    echo $str() . "!"
    

    匿名函数的文档,如 php.net:http://www.php.net/manual/en/functions.anonymous.php

    【讨论】:

    • 好的,所以将其存储在一个变量中:$var = $str()Thanks
    • @KevinDuke 是的,绝对是。请注意,您需要将 2 个参数传递给您的 $str 函数;例如$str(2, 'something')
    猜你喜欢
    • 1970-01-01
    • 2011-10-27
    • 1970-01-01
    • 1970-01-01
    • 2010-12-19
    • 1970-01-01
    • 2014-10-06
    • 1970-01-01
    • 2021-03-18
    相关资源
    最近更新 更多