I have master class that has functions to print each part of website. I have a function that prints master-container which is a div that contains everything. (html/body/#master-container/(all website elements)). Inside that function I have abstract protected function that is used on web page (child class) to generate content that goes inside #master-container. This is part of code in master class:
...
# print content
abstract protected function print_content();
# print master-container
public function print_master_container(){
$output = '
<div id="master-container">
'.$this->print_content().'
</div>
';
echo $output;
}
...
And this is code in child class:
class Starting_page extends Core {
public function print_content(){
$this->print_navbar();
echo 'test';
}
}
...
Now the problem is that it prints everything (both string 'test' and content printed by function $this->print_navbar()
outside of <div id="master-contaiener></div>
. How do I fix this code to actually print everything inside of the div. Screenshot bellow shows the result of the problem inside Page source. Red cursor shows where items (highlighed in yellow) should actually be printed.
If there is need to show more code, say so.
As good people in comments say, the problem was that specific methods used echo
instead of return
. However when return
was used, there would be no output at all. Then @Rasclatt came up with solution for that too which is;
class Starting_page extends Core {
public function print_content(){
# output buffering start
ob_start();
# print navbar
$this->print_navbar();
# declare output buffering content
$output = ob_get_contents();
# add more output data
$output .= 'other content';
# end output buffering and return it
ob_end_clean();
return $output;
}
}
Good thing to notice is that $this->print_navbar()
still uses echo
to print output. In case return
is used then prefix echo
should be added when calling this method.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.