首頁  >  文章  >  後端開發  >  php的閉包是乾嘛的

php的閉包是乾嘛的

angryTom
angryTom原創
2019-08-23 15:27:573399瀏覽

php的閉包是乾嘛的

閉包函數:暫時建立一個沒有名稱的函數,常常當作回呼函數來用。通俗的說就是:子函數可以使用父函數中的局部變量,這種行為叫做閉包。

推薦教學:PHP影片教學

#1、匿名函數賦值

 $demo=function($str){
    echo $str;
  }
  $demo('hello,world');

2、閉包可以從父作用域繼承變量,任何此類型變數都應該用use語言結構傳遞進去。

 $message='hello';
  $example=function() use ($message){
    var_dump($message);
  };
  echo $example();

  結果:hello;

$example=function() use (&$message){
    var_dump($message);
  }
 

  結果:hello;

$message='world';
  echo $example();

  結果:world;

$example=function($arg) use ($message){
    var_dump($arg.' '.$message);
  }
  $example('hello');

  結果:hello world;##hello world; #

以上是php的閉包是乾嘛的的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
上一篇:php的註解方法下一篇:php的註解方法