KittyKate Posted July 21, 2006 Share Posted July 21, 2006 I have a class that may or may not be passed a parameter. How do I deal with this?My first inclination was to declare two constructors. However, this gives me the error: Fatal error: Cannot redeclare supportclass() in "..." on line ...[code]function supportClass() { $htmlGenSupport = new htmlGen(); } function supportClass($html) { $this->htmlGenSupport = $html; }[/code]Knowing PHP lets you overload functions, I tried this, which gives me the error: Parse error: parse error in "..." on line ...[code]function supportClass($html = new htmlGen()) { $this->htmlGenSupport = $html; }[/code]Any suggestions? Link to comment https://forums.phpfreaks.com/topic/15277-overloading-constructors/ Share on other sites More sharing options...
kalivos Posted July 21, 2006 Share Posted July 21, 2006 Would this work for you...?[code] function supportClass($html) { if(isset($html)) { $this->htmlGenSupport = $html; }else{ $htmlGenSupport = new htmlGen(); } }[/code] Link to comment https://forums.phpfreaks.com/topic/15277-overloading-constructors/#findComment-61743 Share on other sites More sharing options...
KittyKate Posted July 21, 2006 Author Share Posted July 21, 2006 Perfect! Java training is coming against me here. I've had it pounded into me that you never write code in a constructor. Guess you can get away with it in PHP. Link to comment https://forums.phpfreaks.com/topic/15277-overloading-constructors/#findComment-61752 Share on other sites More sharing options...
kalivos Posted July 21, 2006 Share Posted July 21, 2006 It may not be proper, but you can :) Link to comment https://forums.phpfreaks.com/topic/15277-overloading-constructors/#findComment-61756 Share on other sites More sharing options...
Joe Haley Posted July 21, 2006 Share Posted July 21, 2006 [quote author=KittyKate link=topic=101407.msg401308#msg401308 date=1153503257]Knowing PHP lets you overload functions, I tried this, which gives me the error: Parse error: parse error in "..." on line ...[/quote][quote author=PhpManual]PHP does not support function overloading, nor is it possible to undefine or redefine previously-declared functions.http://www.php.net/manual/en/language.functions.php[/quote]The exception to this being overloading methods in children. eg:[code]<?phpclass myclass{ function method() { //dostuff }}class myotherclass extends myclass{ function method() { //dostuff parent::method(); // Call the parents method named method() }}?>[/code] Link to comment https://forums.phpfreaks.com/topic/15277-overloading-constructors/#findComment-61819 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.