What is the purpose of the template class in the PHP code provided?
The purpose of the template class in the PHP code provided is to create a reusable structure for generating HTML content with dynamic data. This allows for easier maintenance and organization of the code, as well as promoting separation of concerns between the presentation and logic layers of the application.
<?php
class Template {
private $data = [];
public function setData($key, $value) {
$this->data[$key] = $value;
}
public function render($templateFile) {
ob_start();
extract($this->data);
include $templateFile;
return ob_get_clean();
}
}
// Example usage:
$template = new Template();
$template->setData('title', 'Welcome to my website');
$template->setData('content', 'This is the main content of the page');
echo $template->render('template.php');
?>
Keywords
Related Questions
- What potential pitfalls should be considered when randomly selecting entries from a database in PHP?
- How does the use of register_globals impact the functionality of PHP scripts, particularly when sending emails?
- What best practices should be followed when using preg_match to check if a string meets certain criteria, such as the presence of decimal numbers and commas?