首頁  >  文章  >  後端開發  >  php什麼時候使用閉包

php什麼時候使用閉包

清浅
清浅原創
2019-05-10 14:31:534314瀏覽

php中閉包的使用場景有:1、在動態呼叫靜態類別時;2、在callback函數中使用;3、賦值給一個普通的變數;4、使用use從父域繼承;5、傳遞參數時等等。

php什麼時候使用閉包

php中的閉包的使用場景有:在動態呼叫靜態類別時,在callback函數中使用,賦值給一個普通的變量,使用use從父域繼承以及傳遞參數時

閉包函數

#匿名函數,也叫閉包函數(closures),允許臨時建立一個沒有指定名稱的函數。最常用作回呼函數(callback)參數的值。當然也有其它應用的情況。

使用場景

動態呼叫靜態類別的時候 

<?php
class test
{
    public static function getinfo()
    {
        var_dump(func_get_args());
    }
}
call_user_func(array(&#39;test&#39;, &#39;getinfo&#39;), &#39;hello world&#39;);

在callback函數中使用

<?php
//eg array_walk array_map preg_replace_callback etc
echo preg_replace_callback(&#39;~-([a-z])~&#39;, function ($match) {
    return strtoupper($match[1]);
}, &#39;hello-world&#39;);
// 输出 helloWorld
?>

賦值給一個普通的變數

<?php
$greet = function($name)
{
    printf("Hello %s\r\n", $name);
};
$greet(&#39;World&#39;);
$greet(&#39;PHP&#39;);
?>

使用use從父域繼承  

<?php
$message = &#39;hello&#39;;
// 继承 $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 = &#39;world&#39;;
echo $example();

傳遞參數 

<?php
$example = function ($arg) use ($message) {
    var_dump($arg . &#39; &#39; . $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(&#39;张三&#39;);
});
$factory->set("lisi",function(){
   return new User("李四");
});
echo $factory->get("zhangsan")->getUserName();
echo $factory->get("lisi")->getUserName();

函數中的呼叫 

<?php
 
function call($callback){
            $callback();
    }
call(function() {
    var_dump(&#39;hell world&#39;);
});

    

#

以上是php什麼時候使用閉包的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn