Home > Backend Development > PHP Tutorial > Examples of PHP function overloading techniques

Examples of PHP function overloading techniques

WBOY
Release: 2016-07-25 09:12:07
Original
926 people have browsed it

php, as a weakly typed language, cannot directly implement overloading like strongly typed languages ​​such as java and c++.

Function 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:

  1. function rewrite() {
  2. $args = func_get_args();
  3. if(func_num_args() == 1) {
  4. func1($args[0]);
  5. } else if(func_num_args() == 2) {
  6. func2($args[0], $args[1]);
  7. }
  8. } www.jbxue.com
  9. function func1($arg) {
  10. echo $arg;
  11. }
  12. function func2($arg1, $arg2 ) {
  13. echo $arg1, ' ', $arg2;
  14. }
  15. rewrite('PHP'); //Call func1
  16. rewrite('PHP','China'); //Call func2
Copy code

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

  1. function test($name="小李",$age="23"){
  2. echo $name." ".$age;
  3. }
  4. test();
  5. echo "
    test("a");
  6. echo "
    ";
  7. test("a","b");
Copy code


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