Jump to content


Photo

Overloading Constructors


  • Please log in to reply
4 replies to this topic

#1 KittyKate

KittyKate
  • Members
  • PipPipPip
  • Advanced Member
  • 32 posts

Posted 21 July 2006 - 05:34 PM

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 ...
function supportClass() {
		$htmlGenSupport = new htmlGen();
	}
	
	function supportClass($html) {
		$this->htmlGenSupport = $html;
	}

Knowing PHP lets you overload functions, I tried this, which gives me the error: Parse error: parse error in "..." on line ...
function supportClass($html = new htmlGen()) {
		$this->htmlGenSupport = $html;
	}

Any suggestions?
PHP Version 4.3.2
MySQL version unknown (greater or equal to 3.23)

#2 kalivos

kalivos
  • Members
  • PipPipPip
  • Advanced Member
  • 88 posts
  • LocationCalifornia

Posted 21 July 2006 - 05:37 PM

Would this work for you...?

	function supportClass($html) {
		if(isset($html))
		{
			$this->htmlGenSupport = $html;
		}else{
			$htmlGenSupport = new htmlGen();
		}
	}

Make a donation to phpfreaks. They need your help![br][br]

#3 KittyKate

KittyKate
  • Members
  • PipPipPip
  • Advanced Member
  • 32 posts

Posted 21 July 2006 - 05:52 PM

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.
PHP Version 4.3.2
MySQL version unknown (greater or equal to 3.23)

#4 kalivos

kalivos
  • Members
  • PipPipPip
  • Advanced Member
  • 88 posts
  • LocationCalifornia

Posted 21 July 2006 - 05:55 PM

It may not be proper, but you can :)
Make a donation to phpfreaks. They need your help![br][br]

#5 Joe Haley

Joe Haley
  • Members
  • PipPipPip
  • Advanced Member
  • 103 posts
  • LocationCanada, eh?

Posted 21 July 2006 - 07:54 PM

Knowing PHP lets you overload functions, I tried this, which gives me the error: Parse error: parse error in "..." on line ...


PHP does not support function overloading, nor is it possible to undefine or redefine previously-declared functions.
http://www.php.net/m...e.functions.php


The exception to this being overloading methods in children. eg:

<?php
class myclass
{
    function method()
    {
        //dostuff
    }
}

class myotherclass extends myclass
{
    function method()
    {
        //dostuff
        parent::method();
        // Call the parents method named method()
    }
}
?>

Give a man a fish; you have fed him for today.  Teach a man to fish; and you have fed him for a lifetime
Don't teach men to program. Teach them to fish.

Please, try the RTFM solution before asking for help:
http://php.net/manual/en/index.php




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users