您好,我尝试通过另一个函数回显一个函数的输出,我编写了以下代码:
$users = new user();
class user{
public function userlist(){
//Here is my sql action and then it send the result as output
echo $output;
}
}
现在我有一个包含网站模板的类,这个文件会遍历每个页面。
$html = new html();
class html{
public function output($output){
//echoing some html styles and the template html code..
echo '<div id="body">';
$output;
echo "</div>";
}
}
现在$output
应该在<div id="body">
里面的html页面中,问题是$output
的HTML在div之前被回显,而不是在div内。
简单的方法:
class user{
public function userlist(){
//Here is my sql action and then it send the result as output
return $output;
}
}
class html{
public function output($output){
//echoing some html styles and the template html code..
echo '<div id="body">';
echo $output;
echo "</div>";
}
}
class controller {
function handler(){
$users = new user();
$html = new html();
$html->output($users->userlist());
}
}
现在,在不修改 user
类的情况下,您可以使用输出缓冲来临时保留$users
对象输出,然后在更方便的时间输出它:
class user{
public function userlist(){
//Here is my sql action and then it send the result as output
echo $output;
}
}
class controller {
function handler(){
$users = new user();
$html = new html();
ob_start();
$users->userlist();
$output = ob_get_contents();
ob_end_clean();
$html->output($output);
}
}
但是,我认为如果不修改html::output
方法,您将无法获得预期的结果。
其语义的说明,请参阅有关ob_*
函数的文档。
附录:请注意,许多框架已经在内部使用输出缓冲。文档指出缓冲区是可堆叠的(即,您可以在另一个正在运行的缓冲区之上启动新的缓冲),但请注意正确启动和结束缓冲区,以免弄乱框架内部状态(以及最终的输出),如果您正在使用一个。
你也需要回显$output
public function($output){
//echoing some html styles and the template html code..
echo '<div id="body">';
echo $output;
echo "</div>";
}
或只使用一个衬垫
public function($output){
//echoing some html styles and the template html code..
echo '<div id="body">'. $output . "</div>";
}
您访问变量不正确。由于它是一个字符串,因此您只需在输出中附加或连接它,如下所示:
class html{
public function($output){
//echoing some html styles and the template html code..
echo '<div id="body">'.$output."</div>";
}
}
此外,在第一个函数中,您只需输出 $output 的值,而不是实际将其保存到变量中。如果要按顺序显示内容,则应将数据保存到可以在其他地方正确访问的变量(例如在 return 语句中)或输出初始流,然后运行函数,然后输出剩余的流。