PHP閉包函數(shù)詳解
更新時間:2016年02月13日 22:32:10 投稿:lijiao
這篇文章主要為大家詳細介紹了PHP閉包函數(shù),閉包函數(shù)沒有函數(shù)名稱,直接在function()傳入變量即可 使用時將定義的變量當作函數(shù)來處理,對PHP閉包函數(shù)感興趣的朋友可以參考一下
匿名函數(shù)也叫閉包函數(shù)(closures允許創(chuàng)建一個沒有指定沒成的函數(shù),最經(jīng)常用作回調(diào)函數(shù)參數(shù)的值。
閉包函數(shù)沒有函數(shù)名稱,直接在function()傳入變量即可 使用時將定義的變量當作函數(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 因為繼承變量的值的時候是函數(shù)定義的時候而不是 函數(shù)被調(diào)用的時候
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 關鍵字,而不是通常的 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ù)對數(shù)組中的每個元素應用用戶自定義函數(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));
以上就是關于PHP閉包函數(shù)的相關內(nèi)容,希望對大家的學習有所幫助。
相關文章
快速解決PHP調(diào)用Word組件DCOM權限的問題
下面小編就為大家分享一篇快速解決PHP調(diào)用Word組件DCOM權限的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2017-12-12
PHP實現(xiàn)對xml進行簡單的增刪改查(CRUD)操作示例
這篇文章主要介紹了PHP實現(xiàn)對xml進行簡單的增刪改查(CRUD)操作,結合簡單實例形式分析了php針對xml文件數(shù)據(jù)進行載入、修改等相關操作技巧,需要的朋友可以參考下2017-05-05

