php閉包函數程式碼實例詳解

伊谢尔伦
發布: 2023-03-12 09:46:01
原創
1716 人瀏覽過

這篇文章主要為大家詳細介紹了PHP閉包函數,閉包函數沒有函數名稱,直接在function()傳入變數即可使用時將定義的變數當作函數來處理,對PHP閉包函數有興趣的朋友可以參考一下

匿名函數也叫閉包函數(closures允許建立一個沒有指定沒成的函數,最常用作回調函數參數的值。 ##直接透過定義為匿名函數的變數名稱來呼叫

  $cl = function($name){
    return sprintf('hello %s',name);
  }
  echo $cli('fuck')`
登入後複製

使用use

echo preg_replace_callback('~-([a-z])~', function ($match) {
  return strtoupper($match[1]);
}, 'hello-world');`
登入後複製

example

$message = 'hello';
$example = function() use ($message){
  var_dump($message);
};
echo $example();
//输出hello
$message = 'world';
//输出hello 因为继承变量的值的时候是函数定义的时候而不是 函数被调用的时候
echo $example();
//重置为hello
$message = 'hello';
//此处传引用
$example = function() use(&$message){
 var_dump($message);
};
echo $example();
//输出hello
$message = 'world';
echo $example();
//此处输出world
//闭包函数也用于正常的传值
$message = 'hello';
$example = function ($data) use ($message){
  return "{$data},{$message}";
};

echo $example('world');
登入後複製
以上就是關於PHP閉包函數的相關內容,希望對大家的學習有幫助。

以上是php閉包函數程式碼實例詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!