Home  >  Article  >  php教程  >  PHP小技巧之函数重载

PHP小技巧之函数重载

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

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

PHP代码:

复制代码 代码如下:


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

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

复制代码 代码如下:


function test($name="小李",$age="23"){ 
        echo $name."  ".$age; 
        } 

    test(); 
    echo "
"; 
    test("a"); 
    echo "
"; 
    test("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