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?
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With