首頁 >後端開發 >php教程 >C++、PHP、Javascript、...、對lambda表達式的支持

C++、PHP、Javascript、...、對lambda表達式的支持

WBOY
WBOY原創
2016-08-08 09:26:171511瀏覽

lambda

lambda表達式,也叫Closure(閉包),也叫匿名函數。由於其強大之處,幾乎由所有主流開發語言支持,本文試圖列出大部分語言中lambda表達式的範例程式碼,後續持續更新。

PHP對lambda的支援

<code><span><?php</span><span>$i</span> = <span>12</span>;
<span>$j</span> = <span>33</span>;
<span>$callable</span> = <span><span>function</span><span>()</span><span>use</span><span>(<span>$i</span>, &<span>$j</span>)</span>
{</span><span>echo</span><span>$i</span> . <span>"\n"</span>;
    <span>echo</span><span>$j</span> . <span>"\n"</span>;
};

<span>$callable</span>();

<span>$i</span>++;
<span>$j</span>++;

<span>$callable</span>();
</code>
  • 必須明確引用外部變量,區分值和引用傳遞。

C++對lambda的支援

<code><span>#include <iostream></span><span>using</span><span>namespace</span><span>std</span>;

<span>int</span> main(<span>int</span> argc, <span>char</span>** argv)
{
    <span>int</span> i = <span>12</span>;
    <span>int</span> j = <span>33</span>;
    <span>auto</span> callable = [i, &j](){
        <span>cout</span> << i << endl;
        <span>cout</span> << j << endl;
    };

    callable();

    i++;
    j++;

    callable();
}
</code>
  • 必須顯示引用外部變量,區分值傳遞和引用傳遞。
  • 支援[=][&]等簡易語法來引用全部外部變數。

Javascript

<code><script>
var <span>i</span> = <span>12</span>;
var <span>j</span> = <span>33</span>;

var callable = <span><span>function</span><span>()</span>{</span>
    alert(<span>i</span>);
    alert(<span>j</span>);
}

callable();

<span>i</span>++;
<span>j</span>++;

callable();
</script</code>
  • 無需引用外部變量,外部變數自動可用。
  • 所有變數均依照引用傳遞。

以上就介紹了C++、PHP、Javascript、...、對lambda表達式的支持,包括了方面的內容,希望對PHP教程有興趣的朋友有所幫助。

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