溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

PHP中有哪些閉包函數(shù)

發(fā)布時(shí)間:2021-07-14 15:51:23 來源:億速云 閱讀:108 作者:Leah 欄目:開發(fā)技術(shù)

這篇文章給大家介紹PHP中有哪些閉包函數(shù),內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對(duì)大家能有所幫助。

匿名函數(shù)也叫閉包函數(shù)(closures允許創(chuàng)建一個(gè)沒有指定沒成的函數(shù),最經(jīng)常用作回調(diào)函數(shù)參數(shù)的值。

閉包函數(shù)沒有函數(shù)名稱,直接在function()傳入變量即可 使用時(shí)將定義的變量當(dāng)作函數(shù)來處理

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

直接通過定義為匿名函數(shù)的變量名稱來調(diào)用

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 因?yàn)槔^承變量的值的時(shí)候是函數(shù)定義的時(shí)候而不是 函數(shù)被調(diào)用的時(shí)候
echo $example();
//重置為hello
$message = 'hello';
//此處傳引用
$example = function() use(&$message){
 var_dump($message);
};
echo $example();
//輸出hello
$message = 'world';
echo $example();
//此處輸出world
//閉包函數(shù)也用于正常的傳值
$message = 'hello';
$example = function ($data) use ($message){
  return "{$data},{$message}";
};

echo $example('world');

example

class Cart{
  //在類里面定義常量用 const 關(guān)鍵字,而不是通常的 define() 函數(shù)。
  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() 函數(shù)對(duì)數(shù)組中的每個(gè)元素應(yīng)用用戶自定義函數(shù)。在函數(shù)中,數(shù)組的鍵名和鍵值是參數(shù)
    array_walk($this->products,$callback);
    //回調(diào)匿名函數(shù)
    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));

關(guān)于PHP中有哪些閉包函數(shù)就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

php
AI