douzi4766 2010-06-05 10:57
浏览 26
已采纳

PHP:传递一个带参数的函数作为参数

I'm not sure that silly question, but I ask:
So, if there is an anonymous function I can give it as another anonymous functions parameter, if it has been already stored a variable.
But, whats in that case, if I have stored only one function in a variable, and add the second directly as a parameter into it? Can I add parameters to the non-stored function?

Fist example (thats what i understand :) ):

$func = function($str){ return $str; };
$func2 = function($str){ return $str; };
$var = $func($func2('asd'));

var_dump($var);
// prints out string(3) "asd"

That makes sense for me, but what is with the following one?

$func = function($str){ return $str; };
$var = $func(function($str = "asd"){ return $str; });

var_dump($var);

/** This prints out:
object(Closure)#1 (1) {
  ["parameter"]=>
  array(1) {
    ["$str"]=>
    string(10) ""
  }
}
But why?
*/

And at the end, can someone recommend me a book or an article, from what i can learn this lambda coding feature of php?

  • 写回答

4条回答 默认 最新

  • dongzhukuai8177 2010-06-05 11:04
    关注

    $func simply returns its argument, so:

    $var = $func(function($str = "asd"){ return $str; });
    

    is the same as:

    $var = function($str = "asd"){ return $str; };
    

    The fact that anonymous functions are instances of Closure is an implementation detail the docs warn against relying on. There's nothing special about Closure. It can be implemented in regular PHP thanks to the __invoke magic method.

    On my PHP 5.3.2 installation, Closure has a different representation. The parameter is marked with an "<optional>" string. Perhaps this is a formatting issue.

    php > $func = function($str){ return $str; };
    php > $var = function($str = "asd"){ return $str; };
    php > var_dump($var);
    object(Closure)#2 (1) {
      ["parameter"]=>
      array(1) {
        ["$str"]=>
        string(10) "<optional>"
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度