PHP閉包函數的意義

墨辰丷
發布: 2023-03-29 18:50:01
原創
2386 人瀏覽過

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

匿名函數也叫閉包函數(closures允許建立一個沒有指定沒成的函數,最常用來當作回呼函數參數的值。

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

使用use

$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');
登入後複製

example

class Cart{
  //在类里面定义常量用 const 关键字,而不是通常的 define() 函数。
  const PRICE_BUTTER = 1.00;
  const PRICE_MILK  = 3.00;
  const PRICE_EGGS  = 6.95;

  protected $products = [];
  public function add($product,$quantity){
    $this->products[$product] = $quantity;
  }
  public function getQuantity($product){
    //是否定义了
    return isset($this->products[$product])?$this->products[$product]:FALSE;
  }
  public function getTotal($tax){
    $total = 0.0;
    $callback = function($quantity,$product) use ($tax , &$total){
      //constant 返回常量的值
      //__class__返回类名
      $price = constant(__CLASS__."::PRICE_".strtoupper($product));

      $total += ($price * $quantity)*($tax+1.0);
    };
    //array_walk() 函数对数组中的每个元素应用用户自定义函数。在函数中,数组的键名和键值是参数
    array_walk($this->products,$callback);
    //回调匿名函数
    return round($total,2);

  }
}


$my_cart = new Cart();
$my_cart->add('butter',1);
$my_cart->add('milk',3);
$my_cart->add('eggs',6);


print($my_cart->getTotal(0.05));
登入後複製

#:以上是本篇文的全部內容,希望能對大家的學習有所幫助。

相關推薦:

##php metaphone()函數與php localeconv() 函數實例詳解

#php圖片上傳類別及呼叫方法

#php中array_unshift()修改陣列key注意事項及實例分析

#

以上是PHP閉包函數的意義的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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