


Detailed explanation of anonymous functions and closure functions in PHP
The content of this article is to share with you a detailed explanation of anonymous functions and closure functions in PHP. It has a certain reference value. Friends in need can refer to
PHP’s Anonymous Functions and closure functions
#tags: Anonymous function closure function php closure function php anonymous function function use
##Introduction: Anonymous functions and closure functions are not particularly advanced knowledge, but many friends who are just getting started are always confused, because everyone is accustomed to writing functions just for calling them. What are anonymous functions and closure functions used for?Anonymous functionsphp official explanation is as follows:
Anonymous functions (Anonymous functions), also called closure functions (closures), allow temporary creation of a function without a specified name . The value most commonly used as a callback function argument. Of course, there are other applications as well.
<?php echo preg_replace_callback('~-([a-z])~', function ($match) { return strtoupper($match[1]); }, 'hello-world'); // 输出 helloWorld ?>used as a callback functionIn the above example, the
preg_replace_callback function It requires three parameters. The first parameter is a regular expression used to match data, the second parameter is a function, and the third parameter is the string that needs to be matched. You can also write it like the following
<?php $testFunc = function ($match) { return strtoupper($match[1]); }; echo preg_replace_callback('~-([a-z])~', $testFunc, 'hello-world'); // 输出 helloWorld ?>But we see that we only need to use this method once, so there is no need to name it again, and there is no need to assign it to a variable (the process of assigning values to variables: PHP will automatically Convert it into an object instance of the built-in class Closure and assign it to a variable) Closure functionThe anonymous function in php is also called a closure function, so there is no difference. But the concept of closure in the general sense is not like this. Let's first talk about closure in the traditional sense, and provide an article to compare closures in js with closures (anonymous functions) in php.
Learn Javascript closure (Closure) - Ruan Yifeng
<?php function a(){ $a = 11; function b(){ $b = 22; echo $a; echo $b; } b(); } a(); //报Notice:Undefined variable: a in index.php on line 6 //22 ?>Looking at the above article, we know that it is possible in js. Therefore, anonymous functions in PHP are also called closure functions. You can also pass variables from the parent scope into the closure function (achieving an effect similar to js obtaining parent scope variables). The use keyword is used in PHP, as follows
<?php $count = 0; $a = function() { var_dump($count); }; $b = function() use ($count) { var_dump($count); }; $count++; $c = function() use (&$count) { var_dump($count); }; $count++; $a(); // null Notice: Undefined variable: count in $b(); // int 0 $c(); // int 2 $count++; $b(); // int 0 ?>Is the output of the above example different from what you think?
Analysis: The closure function (anonymous function) uses use to obtain the side effect domain variable when the function is defined, no matter when it is called. If you want to get the variable value when calling, you need to pass it by reference. How to use it depends on the usage scenario.
Lists several common scenariosAs a callback function
//一个我们使用过的例子 <?php/* * 菜谱拆分食物后的拼接 * 参数均不能为空 * */public function mergeFoodsStr($str,array $mapping){ // $str = '白菜半棵、__2__鲍菇两只、__0__一根,__1__两根,三者比例为100:100:15,酱油5克,香油2克,盐1克。';// $mapping = array(// 0 =>array('name' => '胡萝卜','id' => '81' ),// 1 =>array ( 'name' => '萝卜', 'id' => '72'),// 2 =>array ( 'name' => '杏', 'id' => '1841')// ); if(empty($str) || empty($mapping)){ return false; } $strNew = preg_replace_callback('"|__(\d)__|" ',function ($matches) use ($mapping){ return $mapping[$matches[1]]['name']; },$str); $this->log('拼接后的食材字符串',$strNew); return $strNew; }?>
- ## If it is a one-time use function that cannot be reused, you can use the closure function
- etc
The above is the detailed content of Detailed explanation of anonymous functions and closure functions in PHP. For more information, please follow other related articles on the PHP Chinese website!

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Zend Studio 13.0.1
Powerful PHP integrated development environment

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
