Maison > Article > développement back-end > PHP闭包特性应用:代替循环,提高代码性能。_PHP教程
起因是看到了一个简单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="PHP闭包特性应用:代替循环,提高代码性能。_PHP教程" >' alt='<span $filename</span>' /> "<span ; } }); }</span>