Table of Contents
闭包的作用
Home Backend Development PHP Tutorial PHP的学习-PHP的闭包

PHP的学习-PHP的闭包

Jun 13, 2016 pm 12:10 PM
counter function gt use

PHP的学习--PHP的闭包

php的闭包(Closure)也就是匿名函数,是PHP5.3引入的。

闭包的语法很简单,需要注意的关键字就只有use,use是连接闭包和外界变量。

<span style="color: #800080;">$a</span> = <span style="color: #0000ff;">function</span>() <span style="color: #0000ff;">use</span>(<span style="color: #800080;">$b</span>) {}
Copy after login

简单例子如下:

<span style="color: #0000ff;">function</span> <span style="color: #0000ff;">callback</span>(<span style="color: #800080;">$fun</span><span style="color: #000000;">) {</span><span style="color: #800080;">$fun</span><span style="color: #000000;">();}</span><span style="color: #800080;">$msg</span> = "Hello, everyone"<span style="color: #000000;">;</span><span style="color: #800080;">$fun</span> = <span style="color: #0000ff;">function</span> () <span style="color: #0000ff;">use</span>(<span style="color: #800080;">$msg</span><span style="color: #000000;">) {</span><span style="color: #0000ff;">print</span> "This is a closure use string value, msg is: <span style="color: #800080;">$msg</span>. <br>/n"<span style="color: #000000;">;};</span><span style="color: #800080;">$msg</span> = "Hello, everybody"<span style="color: #000000;">;</span><span style="color: #0000ff;">callback</span>(<span style="color: #800080;">$fun</span>);
Copy after login

结果是:This is a closure use string value, msg is: Hello, everyone.
/n

在PHP新开放的闭包语法中, 我们用use来使用闭包外部定义的变量的。这里我们使用了外部变量$msg,定义完之后,又对其值进行了改变,闭包被执行后输出的是原始值。以传值方式传递的基础类型参数,闭包use的值在闭包创建是就确定了。

小应用如下:

<span style="color: #008000;">/*</span><span style="color: #008000;">*  * 一个利用闭包的计数器产生器  * 这里其实借鉴的是python中介绍闭包时的例子...  * 我们可以这样考虑:  *      1. counter函数每次调用, 创建一个局部变量$counter, 初始化为1.  *      2. 然后创建一个闭包, 闭包产生了对局部变量$counter的引用.  *      3. 函数counter返回创建的闭包, 并销毁局部变量, 但此时有闭包对$counter的引用,   *          它并不会被回收, 因此, 我们可以这样理解, 被函数counter返回的闭包, 携带了一个游离态的  *          变量.  *      4. 由于每次调用counter都会创建独立的$counter和闭包, 因此返回的闭包相互之间是独立的.  *      5. 执行被返回的闭包, 对其携带的游离态变量自增并返回, 得到的就是一个计数器.  * 结论: 此函数可以用来生成相互独立的计数器.  </span><span style="color: #008000;">*/</span>  <span style="color: #0000ff;">function</span><span style="color: #000000;"> counter() {      </span><span style="color: #800080;">$counter</span> = 1<span style="color: #000000;">;      </span><span style="color: #0000ff;">return</span> <span style="color: #0000ff;">function</span>() <span style="color: #0000ff;">use</span>(&<span style="color: #800080;">$counter</span>) {<span style="color: #0000ff;">return</span> <span style="color: #800080;">$counter</span> ++<span style="color: #000000;">;};  }  </span><span style="color: #800080;">$counter1</span> =<span style="color: #000000;"> counter();  </span><span style="color: #800080;">$counter2</span> =<span style="color: #000000;"> counter();  </span><span style="color: #0000ff;">echo</span> "counter1: " . <span style="color: #800080;">$counter1</span>() . "<br>/n"<span style="color: #000000;">;  </span><span style="color: #0000ff;">echo</span> "counter1: " . <span style="color: #800080;">$counter1</span>() . "<br>/n"<span style="color: #000000;">;  </span><span style="color: #0000ff;">echo</span> "counter1: " . <span style="color: #800080;">$counter1</span>() . "<br>/n"<span style="color: #000000;">;  </span><span style="color: #0000ff;">echo</span> "counter1: " . <span style="color: #800080;">$counter1</span>() . "<br>/n"<span style="color: #000000;">;  </span><span style="color: #0000ff;">echo</span> "counter2: " . <span style="color: #800080;">$counter2</span>() . "<br>/n"<span style="color: #000000;">;  </span><span style="color: #0000ff;">echo</span> "counter2: " . <span style="color: #800080;">$counter2</span>() . "<br>/n"<span style="color: #000000;">;  </span><span style="color: #0000ff;">echo</span> "counter2: " . <span style="color: #800080;">$counter2</span>() . "<br>/n"<span style="color: #000000;">;  </span><span style="color: #0000ff;">echo</span> "counter2: " . <span style="color: #800080;">$counter2</span>() . "<br>/n"<span style="color: #000000;">;  </span>?>
Copy after login

闭包的作用

1. 减少foreach的循环的代码

比如手册http://php.net/manual/en/functions.anonymous.php 中的例子Cart

<span style="color: #000000;">php</span><span style="color: #008000;">//</span><span style="color: #008000;"> 一个基本的购物车,包括一些已经添加的商品和每种商品的数量。// 其中有一个方法用来计算购物车中所有商品的总价格。该方法使用了一个closure作为回调函数。</span><span style="color: #0000ff;">class</span><span style="color: #000000;"> Cart{    </span><span style="color: #0000ff;">const</span> PRICE_BUTTER  = 1.00<span style="color: #000000;">;    </span><span style="color: #0000ff;">const</span> PRICE_MILK    = 3.00<span style="color: #000000;">;    </span><span style="color: #0000ff;">const</span> PRICE_EGGS    = 6.95<span style="color: #000000;">;     </span><span style="color: #0000ff;">protected</span>   <span style="color: #800080;">$products</span> = <span style="color: #0000ff;">array</span><span style="color: #000000;">();         </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span> add(<span style="color: #800080;">$product</span>, <span style="color: #800080;">$quantity</span><span style="color: #000000;">)    {        </span><span style="color: #800080;">$this</span>->products[<span style="color: #800080;">$product</span>] = <span style="color: #800080;">$quantity</span><span style="color: #000000;">;    }         </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span> getQuantity(<span style="color: #800080;">$product</span><span style="color: #000000;">)    {        </span><span style="color: #0000ff;">return</span> <span style="color: #0000ff;">isset</span>(<span style="color: #800080;">$this</span>->products[<span style="color: #800080;">$product</span>]) ? <span style="color: #800080;">$this</span>->products[<span style="color: #800080;">$product</span>] :               <span style="color: #0000ff;">FALSE</span><span style="color: #000000;">;    }         </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span> getTotal(<span style="color: #800080;">$tax</span><span style="color: #000000;">)    {        </span><span style="color: #800080;">$total</span> = 0.00<span style="color: #000000;">;                 </span><span style="color: #800080;">$callback</span> =            <span style="color: #0000ff;">function</span> (<span style="color: #800080;">$quantity</span>, <span style="color: #800080;">$product</span>) <span style="color: #0000ff;">use</span> (<span style="color: #800080;">$tax</span>, &<span style="color: #800080;">$total</span><span style="color: #000000;">)            {                </span><span style="color: #800080;">$pricePerItem</span> = <span style="color: #008080;">constant</span>(<span style="color: #ff00ff;">__CLASS__</span> . "::PRICE_" .                    <span style="color: #008080;">strtoupper</span>(<span style="color: #800080;">$product</span><span style="color: #000000;">));                </span><span style="color: #800080;">$total</span> += (<span style="color: #800080;">$pricePerItem</span> * <span style="color: #800080;">$quantity</span>) * (<span style="color: #800080;">$tax</span> + 1.0<span style="color: #000000;">);            };        </span><span style="color: #008000;">//</span><span style="color: #008000;">使用用户自定义函数对数组中的每个元素做回调处理</span>        <span style="color: #008080;">array_walk</span>(<span style="color: #800080;">$this</span>->products, <span style="color: #800080;">$callback</span><span style="color: #000000;">);        </span><span style="color: #0000ff;">return</span> <span style="color: #008080;">round</span>(<span style="color: #800080;">$total</span>, 2<span style="color: #000000;">);;    }} </span><span style="color: #800080;">$my_cart</span> = <span style="color: #0000ff;">new</span><span style="color: #000000;"> Cart; </span><span style="color: #008000;">//</span><span style="color: #008000;"> 往购物车里添加条目</span><span style="color: #800080;">$my_cart</span>->add('butter', 1<span style="color: #000000;">);</span><span style="color: #800080;">$my_cart</span>->add('milk', 3<span style="color: #000000;">);</span><span style="color: #800080;">$my_cart</span>->add('eggs', 6<span style="color: #000000;">); </span><span style="color: #008000;">//</span><span style="color: #008000;"> 打出出总价格,其中有 5% 的销售税.</span><span style="color: #0000ff;">print</span> <span style="color: #800080;">$my_cart</span>->getTotal(0.05) . "\n"<span style="color: #000000;">;</span><span style="color: #008000;">//</span><span style="color: #008000;"> The result is 54.29</span>?>
Copy after login

这里如果我们改造getTotal函数必然要使用到foreach。

2. 减少函数的参数

<span style="color: #0000ff;">function</span> html(<span style="color: #800080;">$code</span> , <span style="color: #800080;">$id</span>="", <span style="color: #800080;">$class</span>=""<span style="color: #000000;">){</span><span style="color: #0000ff;">if</span> (<span style="color: #800080;">$id</span> !== "") <span style="color: #800080;">$id</span> = " id = \"<span style="color: #800080;">$id</span>\""<span style="color: #000000;"> ;</span><span style="color: #800080;">$class</span> = (<span style="color: #800080;">$class</span> !== "")? " class =\"<span style="color: #800080;">$class</span>\">":">"<span style="color: #000000;">;</span><span style="color: #800080;">$open</span> = "$code$id$class"<span style="color: #000000;">;</span><span style="color: #800080;">$close</span> = "<span style="color: #800080;">$code</span>>"<span style="color: #000000;">;</span><span style="color: #0000ff;">return</span> <span style="color: #0000ff;">function</span> (<span style="color: #800080;">$inner</span> = "") <span style="color: #0000ff;">use</span> (<span style="color: #800080;">$open</span>, <span style="color: #800080;">$close</span><span style="color: #000000;">){</span><span style="color: #0000ff;">return</span> "<span style="color: #800080;">$open$inner$close</span>"<span style="color: #000000;">;    };}</span>
Copy after login

如果是使用平时的方法,我们会把inner放到html函数参数中,这样不管是代码阅读还是使用都不如使用闭包。

3. 解除递归函数

<span style="color: #000000;">php</span><span style="color: #800080;">$fib</span> = <span style="color: #0000ff;">function</span>(<span style="color: #800080;">$n</span>) <span style="color: #0000ff;">use</span>(&<span style="color: #800080;">$fib</span><span style="color: #000000;">) {    </span><span style="color: #0000ff;">if</span>(<span style="color: #800080;">$n</span> == 0 || <span style="color: #800080;">$n</span> == 1) <span style="color: #0000ff;">return</span> 1<span style="color: #000000;">;    </span><span style="color: #0000ff;">return</span> <span style="color: #800080;">$fib</span>(<span style="color: #800080;">$n</span> - 1) + <span style="color: #800080;">$fib</span>(<span style="color: #800080;">$n</span> - 2<span style="color: #000000;">);}; </span><span style="color: #0000ff;">echo</span> <span style="color: #800080;">$fib</span>(2) . "\n"; <span style="color: #008000;">//</span><span style="color: #008000;"> 2</span><span style="color: #800080;">$lie</span> = <span style="color: #800080;">$fib</span><span style="color: #000000;">;</span><span style="color: #800080;">$fib</span> = <span style="color: #0000ff;">function</span>(){<span style="color: #0000ff;">die</span>('error');};<span style="color: #008000;">//</span><span style="color: #008000;">rewrite $fib variable </span><span style="color: #0000ff;">echo</span> <span style="color: #800080;">$lie</span>(5); <span style="color: #008000;">//</span><span style="color: #008000;"> error   because $fib is referenced by closure</span>
Copy after login

注意上题中的use使用了&,这里不使用&会出现错误fib(n-1)是找不到function的(前面没有定义fib的类型)

所以想使用闭包解除循环函数的时候就需要使用

<span style="color: #000000;">php</span><span style="color: #800080;">$recursive</span> = <span style="color: #0000ff;">function</span> () <span style="color: #0000ff;">use</span> (&<span style="color: #800080;">$recursive</span><span style="color: #000000;">){</span><span style="color: #008000;">//</span><span style="color: #008000;"> The function is now available as $recursive</span>}
Copy after login

这样的形式。

4. 延迟绑定

如果你需要延迟绑定use里面的变量,你就需要使用引用,否则在定义的时候就会做一份拷贝放到use中

<span style="color: #000000;">php</span><span style="color: #800080;">$result</span> = 0<span style="color: #000000;">; </span><span style="color: #800080;">$one</span> = <span style="color: #0000ff;">function</span><span style="color: #000000;">(){    </span><span style="color: #008080;">var_dump</span>(<span style="color: #800080;">$result</span><span style="color: #000000;">);}; </span><span style="color: #800080;">$two</span> = <span style="color: #0000ff;">function</span>() <span style="color: #0000ff;">use</span> (<span style="color: #800080;">$result</span><span style="color: #000000;">){    </span><span style="color: #008080;">var_dump</span>(<span style="color: #800080;">$result</span><span style="color: #000000;">);}; </span><span style="color: #800080;">$three</span> = <span style="color: #0000ff;">function</span>() <span style="color: #0000ff;">use</span> (&<span style="color: #800080;">$result</span><span style="color: #000000;">){    </span><span style="color: #008080;">var_dump</span>(<span style="color: #800080;">$result</span><span style="color: #000000;">);}; </span><span style="color: #800080;">$result</span>++<span style="color: #000000;">; </span><span style="color: #800080;">$one</span>();    <span style="color: #008000;">//</span><span style="color: #008000;"> outputs NULL: $result is not in scope</span><span style="color: #800080;">$two</span>();    <span style="color: #008000;">//</span><span style="color: #008000;"> outputs int(0): $result was copied</span><span style="color: #800080;">$three</span>();    <span style="color: #008000;">//</span><span style="color: #008000;"> outputs int(1)</span>
Copy after login

使用引用和不使用引用就代表了是调用时赋值,还是申明时候赋值

 

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the differences between Huawei GT3 Pro and GT4? What are the differences between Huawei GT3 Pro and GT4? Dec 29, 2023 pm 02:27 PM

Many users will choose the Huawei brand when choosing smart watches. Among them, Huawei GT3pro and GT4 are very popular choices. Many users are curious about the difference between Huawei GT3pro and GT4. Let’s introduce the two to you. . What are the differences between Huawei GT3pro and GT4? 1. Appearance GT4: 46mm and 41mm, the material is glass mirror + stainless steel body + high-resolution fiber back shell. GT3pro: 46.6mm and 42.9mm, the material is sapphire glass + titanium body/ceramic body + ceramic back shell 2. Healthy GT4: Using the latest Huawei Truseen5.5+ algorithm, the results will be more accurate. GT3pro: Added ECG electrocardiogram and blood vessel and safety

What does function mean? What does function mean? Aug 04, 2023 am 10:33 AM

Function means function. It is a reusable code block with specific functions. It is one of the basic components of a program. It can accept input parameters, perform specific operations, and return results. Its purpose is to encapsulate a reusable block of code. code to improve code reusability and maintainability.

Fix: Snipping tool not working in Windows 11 Fix: Snipping tool not working in Windows 11 Aug 24, 2023 am 09:48 AM

Why Snipping Tool Not Working on Windows 11 Understanding the root cause of the problem can help find the right solution. Here are the top reasons why the Snipping Tool might not be working properly: Focus Assistant is On: This prevents the Snipping Tool from opening. Corrupted application: If the snipping tool crashes on launch, it might be corrupted. Outdated graphics drivers: Incompatible drivers may interfere with the snipping tool. Interference from other applications: Other running applications may conflict with the Snipping Tool. Certificate has expired: An error during the upgrade process may cause this issu simple solution. These are suitable for most users and do not require any special technical knowledge. 1. Update Windows and Microsoft Store apps

How to Fix Can't Connect to App Store Error on iPhone How to Fix Can't Connect to App Store Error on iPhone Jul 29, 2023 am 08:22 AM

Part 1: Initial Troubleshooting Steps Checking Apple’s System Status: Before delving into complex solutions, let’s start with the basics. The problem may not lie with your device; Apple's servers may be down. Visit Apple's System Status page to see if the AppStore is working properly. If there's a problem, all you can do is wait for Apple to fix it. Check your internet connection: Make sure you have a stable internet connection as the "Unable to connect to AppStore" issue can sometimes be attributed to a poor connection. Try switching between Wi-Fi and mobile data or resetting network settings (General > Reset > Reset Network Settings > Settings). Update your iOS version:

php提交表单通过后,弹出的对话框怎样在当前页弹出,该如何解决 php提交表单通过后,弹出的对话框怎样在当前页弹出,该如何解决 Jun 13, 2016 am 10:23 AM

php提交表单通过后,弹出的对话框怎样在当前页弹出php提交表单通过后,弹出的对话框怎样在当前页弹出而不是在空白页弹出?想实现这样的效果:而不是空白页弹出:------解决方案--------------------如果你的验证用PHP在后端,那么就用Ajax;仅供参考:HTML code

Detailed explanation of the role and function of the MySQL.proc table Detailed explanation of the role and function of the MySQL.proc table Mar 16, 2024 am 09:03 AM

Detailed explanation of the role and function of the MySQL.proc table. MySQL is a popular relational database management system. When developers use MySQL, they often involve the creation and management of stored procedures (StoredProcedure). The MySQL.proc table is a very important system table. It stores information related to all stored procedures in the database, including the name, definition, parameters, etc. of the stored procedures. In this article, we will explain in detail the role and functionality of the MySQL.proc table

What is the purpose of the 'enumerate()' function in Python? What is the purpose of the 'enumerate()' function in Python? Sep 01, 2023 am 11:29 AM

In this article, we will learn about enumerate() function and the purpose of “enumerate()” function in Python. What is the enumerate() function? Python's enumerate() function accepts a data collection as a parameter and returns an enumeration object. Enumeration objects are returned as key-value pairs. The key is the index corresponding to each item, and the value is the items. Syntax enumerate(iterable,start) Parameters iterable - The passed in data collection can be returned as an enumeration object, called iterablestart - As the name suggests, the starting index of the enumeration object is defined by start. if we ignore

Is watch4pro better or gt? Is watch4pro better or gt? Sep 26, 2023 pm 02:45 PM

Watch4pro and gt each have different features and applicable scenarios. If you focus on comprehensive functions, high performance and stylish appearance, and are willing to bear a higher price, then Watch 4 Pro may be more suitable. If you don’t have high functional requirements and pay more attention to battery life and reasonable price, then the GT series may be more suitable. The final choice should be decided based on personal needs, budget and preferences. It is recommended to carefully consider your own needs before purchasing and refer to the reviews and comparisons of various products to make a more informed choice.

See all articles