Created
December 23, 2010 07:32
-
-
Save jaredwilli/752701 to your computer and use it in GitHub Desktop.
Constructor Overloading using the Php5 __call() method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @constructor overloading using the __call() function | |
* | |
*/ | |
class Player { | |
private $name; | |
private $surname; | |
private $country; | |
private $apt; | |
public function __construct() { | |
$num = func_num_args(); | |
$args = func_get_args(); | |
switch($num) { | |
case 0 : | |
$this->__call('__construct_0', null); | |
break; | |
case 1 : | |
$this->__call('__construct_1', $args); | |
break; | |
case 2 : | |
$this->__call('__construct_2', $args); | |
break; | |
case 3 : | |
$this->__call('__construct_3', $args); | |
break; | |
case 4 : | |
$this->__call('__construct_4', $args); | |
break; | |
default : | |
throw new Exception(); | |
} | |
} | |
public function __construct_0() { | |
echo 'constructor 0' . '<br />'; | |
} | |
public function __construct_1($name) { | |
$this->name = $name; | |
echo 'constructor 1: ' . $this->name . '<br />'; | |
} | |
public function __construct_2($name, $surname) { | |
$this->name = $name; | |
$this->surname = $surname; | |
echo 'constructor 2: ' . $this->name . ' | ' . $this->surname . '<br />'; | |
} | |
public function __construct_3($name, $surname, $country) { | |
$this->name = $name; | |
$this->surname = $surname; | |
$this->country = $country; | |
echo 'constructor 3: '. $this->name .' | '. $this->surname .' | '. $this->country .'<br />'; | |
} | |
public function __construct_4($name, $surname, $country, $apt) { | |
$this->name = $name; | |
$this->surname = $surname; | |
$this->surname = $surname; | |
$this->apt = $apt; | |
echo 'constructor 4: '. $this->name .' | '. $this->surname .' | '. $this->country .' | '. $this->apt .'<br />'; | |
} | |
private function __call($constructor, $arg) { | |
return call_user_func_array( array( $this, $constructor ), $arg ); | |
} | |
} | |
$player1 = new Player('Jared'); | |
$player2 = new Player('Jared', 'Williams'); | |
$player3 = new Player('Jared', 'Williams', 'USA'); | |
$player4 = new Player('Jared', 'Williams', 'USA', '1'); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment