doulangxun7769 2013-10-31 10:47
浏览 32
已采纳

$ provider = function()vs function provider()

I've seen in various coding examples different coding style when creating functions.

What is the difference between creating a function using

$provider = function() { code here }

vs

function provider(){ code here }

Is the first example simply a short version of: $data = provider(); ?
When do we use the first example?

  • 写回答

2条回答 默认 最新

  • dso89762 2013-10-31 10:50
    关注

    No, it isn't. First code is declaration of closure, i.e. anonymous function. It has no name and can be called with identifier that holds it. Second sample is normal function (user-defined function, to be more specific) and, thus, it will be accessible within all scopes via it's name - not like closure, which will be available for calling only within scope, where it was defined.

    You can have as many closures as you wish - they are just callable entities, for example this is valid:

    $provider = function() { Code here }
    $another  = function() { Code here } //same code
    

    -and calling $provider (for example, with call_user_func()) will have nothing to do with $another

    Another significant difference is that closure can accept context parameters like:

    $provider = function() use ($param1, $param2, ...) { Code here }
    

    -so inside it's body context parameters will be available. Context parameters are not like usual arguments - since context parameters defined and exist independent from closure while arguments are evaluated at the moment, when call happened.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?