php什么時(shí)候使用閉包

發(fā)布時(shí)間:2024-03-09
php中的閉包的使用場(chǎng)景有:在動(dòng)態(tài)調(diào)用靜態(tài)類時(shí),在callback函數(shù)中使用,賦值給一個(gè)普通的變量,使用use從父域中繼承以及傳遞參數(shù)時(shí)
閉包函數(shù)
匿名函數(shù),也叫閉包函數(shù)(closures),允許 臨時(shí)創(chuàng)建一個(gè)沒有指定名稱的函數(shù)。最經(jīng)常用作回調(diào)函數(shù)(callback)參數(shù)的值。當(dāng)然也有其它應(yīng)用的情況。
使用場(chǎng)景
動(dòng)態(tài)調(diào)用靜態(tài)類的時(shí)候
<?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 ?>賦值給一個(gè)普通的變量
<?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ù)中的調(diào)用
<?php function call($callback){ $callback(); } call(function() { var_dump('hell world'); });
上一個(gè):ohmite(領(lǐng)先制造商為您打造最可靠的電子元件產(chǎn)品)
下一個(gè):離婚時(shí)該如何分割婚后貸款購買的房產(chǎn)

德國mr品牌介紹
RC-01W4873FT_F 0201 487K現(xiàn)貨購買,風(fēng)華 0201 487KΩ ±1% 1/20W
全民k歌聽不到自己唱的聲音怎么設(shè)置(全民k歌聽不到自己唱的)
戴爾靈越5490平板模式(戴爾靈越5000平板模式可以觸屏嗎)
三星note 3怎么看電子書,三星note2已經(jīng)在手機(jī)里的小說怎么打開
怎么看自己電腦序列號(hào),如何查詢自己電腦的序列號(hào)
為什么編碼器可以在自動(dòng)化行業(yè)中得到廣泛應(yīng)用?
windows7如何設(shè)置兼容性(w7兼容性設(shè)置在哪里)
花灌木常用修剪的方法
三星a9高配版參數(shù)圖片(三星a9系列)
十八禁 网站在线观看免费视频_2020av天堂网_一 级 黄 色 片免费网站_绝顶高潮合集Videos