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');
});