How can classes be utilized to improve the structure and efficiency of PHP code for template handling?

Using classes in PHP can improve the structure and efficiency of template handling by encapsulating related functionality within a class, making the code more organized and easier to maintain. Classes can also provide a way to reuse template-related code across multiple templates, reducing duplication and promoting code reusability.

<?php
class TemplateHandler {
    private $templateData;

    public function __construct($templateData) {
        $this->templateData = $templateData;
    }

    public function renderTemplate($templateFile) {
        ob_start();
        extract($this->templateData);
        include $templateFile;
        return ob_get_clean();
    }
}

// Example usage
$templateData = ['title' => 'Welcome', 'content' => 'Hello, World!'];
$templateHandler = new TemplateHandler($templateData);
echo $templateHandler->renderTemplate('template.php');
?>