Hi, just wondering how is the constructor overloading done in PHP5?As in other OOP languages you can have more constructors for a class, with different params and logic, in PHP I have seen only constructor overloading with predefined parameters like: class MyClass { public function __constructor($nParam1, $nParam2 = 0, $boParam3 = false) { //...some logic } } //so you can use a on parameter constructor or as you need $test1 = new MyClass(5); $test2 = new MyClass(5, 4); $test3 = new MyClass(5, 4, true); But how can I achieve to have a constructor with no param and another with parameter, like: public function __constructor() { //logic } public function __constructor($nParam) { //logic } can I do this? class MyTest { public function __constructor($nParam = null) { if($nParam == null) { } else { } } //and then $test4 = new MyTest(); $test5 = new MyTest(3); I found a link to a code, which I am not sure about if it is valid in PHP5 Many thanks Ben }
And almost forgot the mentioned code http://www.webscriptexpert.com/Php/Constructor overloading Java and PHP5/
You could do the above, but for organization sake, you should have two constructors instead: construct constructA Peace,
hmm... What do you mean by two constructors: construct constructA ?????????? Can you explain it? As of my knowledge, PHP does not support Java like constructor overloading, so this is not valid: class MyClass { function MyClass() { } function MyClass($value) { print "$value"; } /*nor the following: function __construct() { } function __construct($value) { print "$value"; } */ } $test = new MyClass(); $otherTest = new MyClass(1); If I am wrong, please correct me. My main goal is to have a constructor with different number of parameters of different type - providing different logic, therefore the parameter names themself should be unique and not to let the developer into confusion, so the default value solution is not an ideal solution. btw:my post contained 'constructor' instead of 'construct' so sorry for that. Thanks Ben
PHP5 does not support object overloading in the same sense that say Java does it. You cannot do say <?php class MyClass { public function __construct() { } public function __construct($var) { } } PHP: You have two options one to set default values for the extra fields so say public function __construct($var = 5; $varb = 6;) { } PHP: The second option would be to create something like public function __construct() { $num_args=func_num_args(); switch($num_args) { case 0: print 'do something'; break; case 1: $arg_one=func_get_arg(0); print $arg_one; break; } } PHP: Hope that helps