使用php析构函数适合显示HTML吗? [英] Is using php destructor appropriate for displaying HTML?
问题描述
如果实现了一个通过构造页面并调用各种方法来为页面构建HTML的类,那么在析构函数中定义该类的显示/回显部分是否合适?
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?
不是使用显式的 Class:displayHTML();
方法,而是使用了 echo $ this-> html
在析构函数中,并且只要您准备显示调用 unset($ object);
,它将显示它吗?
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.
如果您不想拥有/调用 displayHTML()
或 render()
方法,在 __ toString()
中实现该部分,然后回显实例。
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;
这篇关于使用php析构函数适合显示HTML吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!