PHP閉包函數詳解

來源:互聯網
上載者:User
匿名函數也叫閉包函數(closures允許建立一個沒有指定沒成的函數,最經常用作回呼函數參數的值。

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

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

直接通過定義為匿名函數的變數名稱來調用

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閉包函數的相關內容,希望對大家的學習有所協助。

以上就介紹了PHP閉包函數詳解,包括了方面的內容,希望對PHP教程有興趣的朋友有所協助。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.