Home > Backend Development > PHP Tutorial > Application of PHP closure features: replacing loops and improving code performance. _PHP Tutorial

Application of PHP closure features: replacing loops and improving code performance. _PHP Tutorial

WBOY
Release: 2016-07-20 11:14:14
Original
1485 people have browsed it

起因是看到了一个简单php上传脚本:http://www.nowamagic.net/librarys/veda/detail/1384

我重构了一下,主要是用匿名函数代替了foreach循环,利用了闭包的新特性,从而也提高了性能。需要注意的是闭包并不就完全等于匿名函数,闭包是通过匿名函数实现的,跟use关键字的使用有关。

记录下就当抛砖引玉了,毕竟随着php众多新特性的加入,我们程序员也要与时俱进不断优化代码,重构自身。
以下是重构后的php部分:

<span $img</span> = <span $_FILES</span>['img'<span ];
</span><span if</span> (<span $img</span><span )
{
    </span><span //</span><span 文件存放目录,和本php文件同级</span>
    <span $dir</span> = <span dirname</span>(<span __file__</span><span );

    </span><span array_walk</span>(<span $img</span>['tmp_name'], <span function</span> (<span $value</span>) <span use</span>(<span $dir</span>,<span $img</span><span )
    {    </span><span //</span><span 保证$img['tmp_name']和$img['name']中索引的对应</span>
        <span $filename</span> = <span $img</span>['name'][<span array_search</span>(<span $value</span>, <span $img</span>['tmp_name'<span ])];
        </span><span //</span><span 设置上传路径</span>
         <span $savepath</span>="<span $dir</span>\\<span $filename</span>"<span ;
         </span><span //</span><span 上传,并返回状态</span>
        <span $state</span> = <span move_uploaded_file</span>(<span $value</span>, <span $savepath</span><span );
        </span><span //</span><span 如果上传成功,预览</span>
        <span if</span>(<span $state</span><span )
        {
               </span><span echo</span> "<img src='<span $filename</span>' alt='<span $filename</span>' /> "<span ;
        }
    });
}</span>
Copy after login

 

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/440316.htmlTechArticle起因是看到了一个简单php上传脚本:http://www.nowamagic.net/librarys/veda/detail/1384 我重构了一下,主要是用匿名函数代替了foreach循环,利用了闭包...
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template