深入理解php 匿名函數和 Closure

來源:互聯網
上載者:User

標籤:http   io   os   使用   ar   sp   cti   log   on   

而在PHP 5.3發布的時候, 其中有一條new feature就是支援閉包/Lambda Function, 我第一反應是以為zval新增了一個IS_FUNCTION, 但實際上是構造了一個PHP 5.3引入的Closure”類”的執行個體, Closure類的建構函式是私人的, 所以不能被直接執行個體化, 另外Closure類是Final類, 所以也不能做為基類派生子類.

 

  1. //php-5.3.0  
  2. $class = new ReflectionClass("Closure");  
  3. var_dump($class->isInternal());  
  4. var_dump($class->isAbstract() );  
  5. var_dump($class->isFinal());  
  6. var_dump($class->isInterface());  
  7. //輸出:  
  8. bool(true)  
  9. bool(false)  
  10. bool(true)  
  11. bool(false)  
  12. ?>  

  而PHP 5.3中對閉包的支援, 也僅僅是把要保持的外部變數, 做為Closure對象的”Static屬性”(並不是普通意義上的可遍曆/訪問的屬性).

 

  1. //php-5.3.0  
  2. $b = "laruence";  
  3. $func = function($a) use($b) {};  
  4. var_dump($func);  
  5. /* 輸出:  
  6. object(Closure)#1 (2) {  
  7. ["static"]=>  
  8.  array(1) {  
  9. ["b"]=> string(8) "laruence"   
  10. }    
  11. ["parameter"]=>   
  12. array(1) {   
  13.  ["$a"]=> string(10) "<required>"   
  14.  }   
  15.  }   
  16.  */  

 

 

閉包函數也可以作為變數的值來使用。PHP 會自動把此種運算式轉換成內建類 Closure 的對象執行個體。把一個 closure 對象賦值給一個變數的方式與普通變數賦值的文法是一樣的,最後也要加上分號:

<?php
$greet = function($name)
{
    printf("Hello %s\r\n", $name);
};

$greet(‘World‘);
$greet(‘PHP‘);
?>

仔細看下面的例子...看看範圍的不同

<?php
$result = 0;

$one = function()
{ var_dump($result); };

$two = function() use ($result)
{ var_dump($result); };

$three = function() use (&$result)
{ var_dump($result); };

$result++;

$one();    // outputs NULL: $result is not in scope
$two();    // outputs int(0): $result was copied
$three();    // outputs int(1)
?>

 

<?php
//set up variable in advance
$myInstance = null;

$broken = function() uses ($myInstance)
{
    if(!empty($myInstance)) $myInstance->doSomething();
};

$working = function() uses (&$myInstance)
{
    if(!empty($myInstance)) $myInstance->doSomething();
}

//$myInstance might be instantiated, might not be
if(SomeBusinessLogic::worked() == true)
{
    $myInstance = new myClass();
}

$broken();    // will never do anything: $myInstance will ALWAYS be null inside this closure.
$working();    // will call doSomething if $myInstance is instantiated

?>

深入理解php 匿名函數和 Closure

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.