PHP 閉包,簡易記數工廠



閉包的使用



php5.3開始支援閉包



// 簡易的計數器工廠模式

function counterFactory() {

$counter = 1;

return function() use(&$counter) {

return $counter++;

};

}

$counter1 = counterFactory();

$counter2 = counterFactory();

echo "counter1: " . $counter1() . "<br />";

echo "counter1: " . $counter1() . "<br />";

echo "counter1: " . $counter1() . "<br />";

echo "counter1: " . $counter1() . "<br />";

echo "counter2: " . $counter2() . "<br />";

echo "counter2: " . $counter2() . "<br />";

echo "counter2: " . $counter2() . "<br />";

// counter1: 1

// counter1: 2

// counter1: 3

// counter1: 4

// counter2: 1

// counter2: 2

// counter2: 3






留言

這個網誌中的熱門文章

成人剪舌繫帶聽過嗎?我剪了!!

Scp - ssh 的遠端檔案傳輸指令

關於RCA