tags:

views:

73

answers:

4

If a class is implemented that builds HTML for a page by constructing it and calling various methods, is it appropriate to define the display/echo part of the class within the destructor?

Instead of having a explicit Class:displayHTML(); method, having the echo $this->html in the destructor and whenever you are ready to display call unset($object); which would display it?

I know the destructor probably is not the best place for this but wonder what others thoughts are on this?

+6  A: 

Which of these two has a more obvious outcome?

unset($object);

or:

$object->displayHTML();

Think about that, and then go read about the Principle of Least Astonishment.

Dominic Rodger
Agreed. Having the destructor output HTML is a completely unexpected outcome.
meagar
This is a great reference link and I wish I could accept two answers!
Chris
+9  A: 

That doesnt sound feasible to me. unset does not equal echo. It's a fundamentally different thing. Also, keep in mind that objects are not only destroyed on unset but also when they are no longer referenced and/or when the script terminates. That has a lot potential for unwanted side effects.

If you dont want to have/call a displayHTML() or render() method, implement that part in __toString() and just echo the instance.

class HTMLSomething
{
    /* ... */
    public function __toString()
    {
        /* create $output */
        return $output;
    }
}
$something = new HTMLSomething;
echo $something;
Gordon
Hannes
I totally forgot about the __toString method. Great answer.
Chris
also, the __deconstruct() is also called when the script ends, so even without unset it would be called, which could lead to some weird behavior
Hannes
+1  A: 

Seems like a bad idea. I don't really see this:

unset($view);

as better than this

$view->displayHTML();

It seems the only real advantage is that you don't really need to call unset() (since at the end of the script that should happen).

However, is that really a good thing? How then do you prevent it from being displayed? Once it's set you couldn't. Or you would need a special clear() function to unset the output before it's automatically output by the destructor.

To me, I don't see an advantage here.

Tim Lytle
+1  A: 

Hello,

This is not the way to go because you do not have complete control over your destructor. The destructor will be called when your script finishes, but you may not want to display anything under certain conditions (say: load, validate, validation fails, display something else).

Also, as Dominic pointed out, there is the matter of readability. You don't want to read your code a year later and say: Why do I unset the object? WTF was I thinking back then?! . As you can see this will increase the WTF/minute ratio and we all know that is a bad thing.

Alin Purcaru