Home > php教程 > php手册 > body text

PHP小技巧之函数重载

WBOY
Release: 2016-06-13 09:34:27
Original
814 people have browsed it

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");

Related labels:
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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template