這篇文章將為大家詳細講解有關php如何使用閉包,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
php中的閉包的使用場景有:在動態(tài)調用靜態(tài)類時,在callback函數(shù)中使用,賦值給一個普通的變量,使用use從父域中繼承以及傳遞參數(shù)時
閉包函數(shù)
匿名函數(shù),也叫閉包函數(shù)(closures),允許 臨時創(chuàng)建一個沒有指定名稱的函數(shù)。最經(jīng)常用作回調函數(shù)(callback)參數(shù)的值。當然也有其它應用的情況。
使用場景
動態(tài)調用靜態(tài)類的時候
<?php class test { public static function getinfo() { var_dump(func_get_args()); } } call_user_func(array('test', 'getinfo'), 'hello world');
在callback函數(shù)中使用
<?php //eg array_walk array_map preg_replace_callback etc echo preg_replace_callback('~-([a-z])~', function ($match) { return strtoupper($match[1]); }, 'hello-world'); // 輸出 helloWorld ?>
賦值給一個普通的變量
<?php $greet = function($name) { printf("Hello %s\r\n", $name); }; $greet('World'); $greet('PHP'); ?>
使用use從父域中繼承
<?php $message = 'hello'; // 繼承 $message $example = function () use ($message) { var_dump($message); }; echo $example(); // Inherit by-reference $example = function () use (&$message) { var_dump($message); }; echo $example(); // The changed value in the parent scope // is reflected inside the function call $message = 'world'; echo $example();
傳遞參數(shù)
<?php $example = function ($arg) use ($message) { var_dump($arg . ' ' . $message); }; $example("hello");
OO中的使用
<?php class factory{ private $_factory; public function set($id,$value){ $this->_factory[$id] = $value; } public function get($id){ $value = $this->_factory[$id]; return $value(); } } class User{ private $_username; function __construct($username="") { $this->_username = $username; } function getUserName(){ return $this->_username; } } $factory = new factory(); $factory->set("zhangsan",function(){ return new User('張三'); }); $factory->set("lisi",function(){ return new User("李四"); }); echo $factory->get("zhangsan")->getUserName(); echo $factory->get("lisi")->getUserName();
函數(shù)中的調用
<?php function call($callback){ $callback(); } call(function() { var_dump('hell world'); });
關于php如何使用閉包就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
另外有需要云服務器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務器、裸金屬服務器、高防服務器、香港服務器、美國服務器、虛擬主機、免備案服務器”等云主機租用服務以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應用場景需求。
當前題目:php如何使用閉包-創(chuàng)新互聯(lián)
文章來源:http://chinadenli.net/article18/dephgp.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供關鍵詞優(yōu)化、網(wǎng)頁設計公司、微信公眾號、微信小程序、虛擬主機、域名注冊
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉載內(nèi)容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)