Jump to content

Archived

This topic is now archived and is closed to further replies.

KittyKate

Overloading Constructors

Recommended Posts

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?

Share this post


Link to post
Share on other sites
Would this work for you...?

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

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
[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]<?php
class myclass
{
    function method()
    {
        //dostuff
    }
}

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

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.