Home  >  Article  >  php教程  >  PHP实现函数重载

PHP实现函数重载

WBOY
WBOYOriginal
2016-06-13 09:34:421376browse

本来php?name=PHP">PHP是不支持函数重载的!

php 作为一种弱类型语言,本身不能像强类型如java ,c++那样,直接的实现重载。不过可以通过一些方法,间接的实现重载。

1.可以使用func_get_args()和func_num_args()这两个函数实现函数的重载!!

PHP代码:

    <span>function</span><span> rewrite() {   
            </span><span>$args</span> = <span>func_get_args</span><span>();   
            </span><span>if</span>(<span>func_num_args</span>() == 1<span>) {   
                    func1(</span><span>$args</span>[0<span>]);   
            } </span><span>else</span> <span>if</span>(<span>func_num_args</span>() == 2<span>) {   
                    func2(</span><span>$args</span>[0], <span>$args</span>[1<span>]);   
            }   
    }   
      
    </span><span>function</span> func1(<span>$arg</span><span>) {   
            </span><span>echo</span> <span>$arg</span><span>;   
    }   
      
    </span><span>function</span> func2(<span>$arg1</span>, <span>$arg2</span><span>) {   
            </span><span>echo</span> <span>$arg1</span>, ' ', <span>$arg2</span><span>;   
    }   
      
    rewrite(</span>'PHP'); <span>//</span><span>调用func1   </span>
    rewrite('PHP','China'); <span>//</span><span>调用func2   </span>

2.使用默认值,从而根据输入,得到自己想要的结果:

 <span>function</span> test(<span>$name</span>="小李",<span>$age</span>="23"<span>){  
        </span><span>echo</span> <span>$name</span>."  ".<span>$age</span><span>;  
        }  
  
    test();  
    </span><span>echo</span> "<br/>"<span>;  
    test(</span>"a"<span>);  
    </span><span>echo</span> "<br/>"<span>;  
    test(</span>"a","b"); 

 

 

 

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