Home  >  Article  >  Backend Development  >  C++, PHP, Javascript,..., support for lambda expressions

C++, PHP, Javascript,..., support for lambda expressions

WBOY
WBOYOriginal
2016-08-08 09:26:171439browse

lambda

lambda expression, also called Closure (closure), also called anonymous function. Due to its power, it is supported by almost all mainstream development languages. This article attempts to list sample codes for lambda expressions in most languages ​​and will be continuously updated in the future.

PHP’s support for lambdas

<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>
  • must explicitly reference external variables, distinguishing between value and reference passing.

C++’s support for 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>
  • must explicitly refer to external variables, distinguishing between value transfer and reference transfer.
  • Supports simple syntax such as [=][&] to reference all external variables.

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>
  • No need to reference external variables, external variables are automatically available.
  • All variables are passed by reference.

The above has introduced the support for lambda expressions in C++, PHP, Javascript, ..., including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn