Home >Backend Development >PHP Tutorial >那些未曾了解的PHP函数和功能_PHP

那些未曾了解的PHP函数和功能_PHP

WBOY
WBOYOriginal
2016-06-01 12:20:29782browse

PHP的真正威力源自于它的函数,但有些PHP函数并没有得到充分的利用,也并不是所有人都会从头到尾一页一页地阅读手册和函数参考,这里将向您介绍这些实用的函数和功能。

1、任意参数数目的函数

你可能已经知道,PHP允许定义可选参数的函数。但也有完全允许任意数目的函数参数的方法。以下是可选参数的例子:

<ol class="dp-xml">
<li class="alt"><span><span>以下为引用的内容:  </span></span></li>
<li><span> </span></li>
<li class="alt"><span>//functionwith2optionalarguments  </span></li>
<li>
<span>functionfoo($</span><span class="attribute"><font color="#ff0000">arg1</font></span><span>=”,$</span><span class="attribute"><font color="#ff0000">arg2</font></span><span>=”){  </span>
</li>
<li class="alt"><span> </span></li>
<li><span>echo“arg1:$arg1\n”;  </span></li>
<li class="alt"><span>echo“arg2:$arg2\n”;  </span></li>
<li><span> </span></li>
<li class="alt"><span>}  </span></li>
<li><span> </span></li>
<li class="alt"><span>foo(‘hello’,'world’);  </span></li>
<li><span>/*prints:  </span></li>
<li class="alt"><span>arg1:hello  </span></li>
<li><span>arg2:world  </span></li>
<li class="alt"><span>*/  </span></li>
<li><span> </span></li>
<li class="alt"><span>foo();  </span></li>
<li><span>/*prints:  </span></li>
<li class="alt"><span>arg1:  </span></li>
<li><span>arg2:  </span></li>
<li class="alt"><span>*/ </span></li>
</ol>

现在让我们看看如何建立能够接受任何参数数目的函数。这一次需要使用func_get_args()函数:

  1. 以下为引用的内容:  
  2.  
  3. //yes,theargumentlistcanbeempty  
  4. functionfoo(){  
  5.  
  6. //returnsanarrayofallpassedarguments  
  7. $args=func_get_args();  
  8.  
  9. foreach($argsas$k=>$v){  
  10. echo“arg”.($k+1).”:$v\n”;  
  11. }  
  12.  
  13. }  
  14.  
  15. foo();  
  16. /*printsnothing*/  
  17.  
  18. foo(‘hello’);  
  19. /*prints  
  20. arg1:hello  
  21. */  
  22.  
  23. foo(‘hello’,‘world’,‘again’);  
  24. /*prints  
  25. arg1:hello  
  26. arg2:world  
  27. arg3:again  
  28. */ 
<span>
    </span>
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