Guest User

PHP "method overloading" example

a guest
Jan 13th, 2011
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.77 KB | None | 0 0
  1. <?php
  2.  
  3. class Foo
  4. {
  5.     public function bar()
  6.     {
  7.         $argsCount = func_num_args();
  8.         switch ($argsCount) {
  9.             case 1:
  10.                 return $this->_barWithOneArgument(func_get_arg(0));
  11.                 break;
  12.             case 2:
  13.                 return $this->_barWithTwoArguments(func_get_arg(0), func_get_args(1));
  14.                 break;
  15.             default:
  16.                 throw new InvalidArgumentException();
  17.         }
  18.     }
  19.    
  20.     private function _barWithOneArgument($a)
  21.     {
  22.         return "Hello, I'm one argument function";
  23.     }
  24.    
  25.     private function _barWithTwoArguments($a, $b)
  26.     {
  27.         return "Hello, I'm function with two arguments";
  28.     }
  29. }
  30.  
  31. $foo = new Foo();
  32. var_dump($foo->bar(1));
  33. var_dump($foo->bar(1, 2));
Advertisement
Add Comment
Please, Sign In to add comment