Created
August 18, 2018 13:04
-
-
Save antelove19/ea41114b2de624170cfc3fa46597a69c to your computer and use it in GitHub Desktop.
Overload Constructor in PHP
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 | |
| class myClass { | |
| public $param1 = 'a'; | |
| public $param2 = 'b'; | |
| public function __construct($param1 = NULL, $param2 = NULL) { | |
| if ($param1 == NULL && $param2 == NULL) { | |
| // $this->param1 = $param1; | |
| // $this->param2 = $param2; | |
| } elseif ($param1 == NULL && $param2 !== NULL) { | |
| // $this->param1 = $param1; | |
| $this->param2 = $param2; | |
| } elseif ($param1 !== NULL && $param2 == NULL) { | |
| $this->param1 = $param1; | |
| // $this->param2 = $param2; | |
| } else { | |
| $this->param1 = $param1; | |
| $this->param2 = $param2; | |
| } | |
| } | |
| } | |
| // $myObject = new myClass(); | |
| // $myObject = new myClass(NULL, 2); | |
| $myObject = new myClass(1, ''); | |
| // $myObject = new myClass(1, 2); | |
| echo $myObject->param1; | |
| echo "<br />"; | |
| echo $myObject->param2; | |
| ?> |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://stackoverflow.com/questions/2169448/why-cant-i-overload-constructors-in-php/51908855#51908855