Created
April 29, 2021 09:49
-
-
Save catwhocode/d35ed43b23d26d314fea5fc3f736231f to your computer and use it in GitHub Desktop.
This file contains 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 | |
// taken from: https://www.amitmerchant.com/multiple-constructors-php/ | |
class Animal | |
{ | |
public function __construct() | |
{ | |
$arguments = func_get_args(); | |
$numberOfArguments = func_num_args(); | |
if (method_exists($this, $function = '__construct'.$numberOfArguments)) { | |
call_user_func_array(array($this, $function), $arguments); | |
} | |
} | |
public function __construct1($a1) | |
{ | |
echo('__construct with 1 param called: '.$a1.PHP_EOL); | |
} | |
public function __construct2($a1, $a2) | |
{ | |
echo('__construct with 2 params called: '.$a1.','.$a2.PHP_EOL); | |
} | |
public function __construct3($a1, $a2, $a3) | |
{ | |
echo('__construct with 3 params called: '.$a1.','.$a2.','.$a3.PHP_EOL); | |
} | |
} | |
$o = new Animal('sheep'); | |
$o = new Animal('sheep','cat'); | |
$o = new Animal('sheep','cat','dog'); | |
// __construct with 1 param called: sheep | |
// __construct with 2 params called: sheep,cat | |
// __construct with 3 params called: sheep,cat,dog |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment