duancilan5124 2018-09-21 11:18
浏览 290
已采纳

带两个括号的PHP函数:calc(1)(2)

JavaScript:

function calc(x) {
  return function(y) {
     return x + y;
  };
}

console.log(calc(1)(2));

This will return 3.

I tried the same with PHP:

function calc($x) {
    return function($y) { 
        return $x + $y; 
    };
}

echo calc(1)(2);

This will return 2. And I get an E_NOTICE:

E_NOTICE : type 8 -- Undefined variable: x -- at line 4

Why is the variable x undefined? Is it because that wouldn't work with PHP or am I doing something wrong?

</div>
  • 写回答

1条回答 默认 最新

  • douqun1977 2018-09-21 11:20
    关注

    it's called a closure :

    http://php.net/manual/en/class.closure.php

    http://php.net/manual/en/functions.anonymous.php

    function calc($x) {
        return function($y) use($x){ 
            return $x + $y; 
        };
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部