An alternative method of PHP function overloading--an example of pseudo-overload detailed _php

Source: Internet
Author: User

Workaround for function overloading-pseudo overload, look at a concrete instance code below.

? An alternative to PHP//function overloading-pseudo overload///Indeed, there is no function overload in PHP, so many times we can't do some processing, and sometimes we have to define n parameters at the back of the function//after seeing the Func_get_arg,func_get_args,

Func_num_args, what do you think of these three functions?

function Testone ($a) {echo (' One argument is so ');}

function Testtwo ($a, $b) {echo (' two arguments in this way ');}

function Testthree ($a, $b, $c) {echo (' Black, this is three parameters ');}
  function test () {$argNum = Func_num_args (); This paragraph can actually use $_arg = Func_get_args () to get all the parameters, just to use the array, not convenient for my expression below, hehe for ($i = 0; $i < $argNum; $i + +) {$_arg
 _ {$i} = Func_get_arg ($i);
   Switch ($argNum) {case 1:testone ($_arg_1);
  break;
   Case 2:testtwo ($_arg_1, $_arg_2);
  break;
   Case 3:testthree ($_arg_1, $_arg_2, $_arg_3);
  break;
   Default:echo (' This is the case without parameters ');
 break;
} test ();
Echo (");
Test (1);
Echo (");
Test (1, 2);
Echo (");

Test (1, 2, 3);

These are only used in functions, in fact, the most important or in the use of classes//If these are used in the class I do not need to worry about whether the constructor has a few parameters, is not it?
 Class Test {var $a = 0;

 var $b = 0; Function Test () {$argNum = Func_num_args ();
  $_arg = Func_get_args ();
   Switch ($argNum) {Case 1: $this-> test1 ($_arg [0]);
  break;
   Case 2: $this-> test2 ($_arg [0], $_arg [1]);
  break;
   Default: $this-> a = 0;
   $this-> b = 1;
  break;
 } function Test1 ($a) {$this-> a = $a;
  function test2 ($a, $b) {$this-> a = $a;
 $this-> b = $b;
 }}?>

The above is the entire contents of this article, I hope you can enjoy.

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.