Home > Backend Development > PHP Tutorial > Implementing function overloading in PHP_PHP tutorial

Implementing function overloading in PHP_PHP tutorial

WBOY
Release: 2016-07-13 10:29:18
Original
1145 people have browsed it

Originally php?name=PHP">PHP does not support function overloading!

As a weakly typed language, php itself cannot directly implement overloading like strongly typed languages ​​such as java and c++. However, overloading can be achieved indirectly through some methods.

1. You can use the two functions func_get_args() and func_num_args() to implement function overloading!!

PHP code:

    <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>
Copy after login

2. Use the default value to get the results you want based on the input:

 <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"); 
Copy after login

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/777735.htmlTechArticleOriginally php?name=PHP"PHP does not support function overloading! As a weakly typed language, php It cannot directly implement overloading like strong types such as java and c++, but it can be implemented through some...
Related labels:
php
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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template