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

匿名函數也叫閉包函數(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中有哪些閉包函數-創新互聯
網頁鏈接:http://www.yijiale78.com/article26/discjg.html
成都網站建設公司_創新互聯,為您提供靜態網站、云服務器、網站維護、品牌網站設計、品牌網站制作、做網站
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯