Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using php destructor appropriate for displaying HTML?

Tags:

php

destructor

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?

like image 797
Chris Avatar asked Dec 02 '22 04:12

Chris


2 Answers

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;
like image 62
Gordon Avatar answered Dec 24 '22 10:12

Gordon


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.

like image 28
Dominic Rodger Avatar answered Dec 24 '22 08:12

Dominic Rodger