轉:php中的匿名函數和閉包(closure)

來源:互聯網
上載者:User

標籤:copy   變數   hello   http   函數返回   .net   bsp   tle   沒有   

一:匿名函數 (在php5.3.0 或以上才能使用)

     php中的匿名函數(Anonymous functions), 也叫閉包函數(closures), 允許指定一個沒有名稱的函數。最常用的就是回呼函數的參數值。(http://php.net/manual/zh/functions.anonymous.php)

     匿名函數的定義:

$closureFunc = function(){    .... };

   eg: 把匿名函數賦值給變數,通過變數來調用

 $closureFunc = function($str){   echo $str;  };  $closureFunc("hello world!");

  輸出: hello world!

 

二:閉包

 2.1  將匿名函數放在普通函數中,也可以將匿名函數返回,這就構成了一個簡單的閉包 

function closureFunc1(){    $func = function(){        echo "hello";    };    $func();}closureFunc1();//輸出: hello

2.2  在匿名函數中引用局部變數

function closureFunc2(){    $num = 1;    $func = function(){        echo $num;    };    $func();}closureFunc2();//Notice: Undefined variable: num

上面的函數運行後,會報Notice錯誤,說明我們不能在匿名函數中這樣使用局部變數,這時候就要引用一個php的關鍵字 use, 代碼如下

轉:php中的匿名函數和閉包(closure)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.