Example of PHP function overloading tips

Source: Internet
Author: User
Example of PHP function overloading tips

Php, as a weak type language, cannot directly implement overload like a strong type such as java or c ++.

Function overloading can be indirectly implemented through some methods.

1. you can use the func_get_args () and func_num_args () functions to overload functions.
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

2. use the default value to obtain the desired result based on the input:

  1. Function test ($ name = "Xiao Li", $ age = "23 "){
  2. Echo $ name. "". $ age;
  3. }
  4. Test ();
  5. Echo"
    ";
  6. Test ("");
  7. Echo"
    ";
  8. Test ("a", "B ");

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.