Is using php destructor appropriate for displaying HTML?

瘦欲@ 提交于 2019-12-23 12:57:37

问题


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?


回答1:


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;



回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/3933206/is-using-php-destructor-appropriate-for-displaying-html

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!