What are some best practices for replacing variables in PHP templates without using global variables?

When replacing variables in PHP templates without using global variables, it is recommended to pass the variables as parameters to the template function or method. This helps to keep the code modular and avoid potential conflicts with global variables. By passing variables explicitly, you can ensure that the template has access to only the necessary data.

<?php
function render_template($template, $data) {
    extract($data);
    ob_start();
    include $template;
    return ob_get_clean();
}

// Example usage
$template = 'template.php';
$data = ['name' => 'John Doe', 'age' => 30];
echo render_template($template, $data);
?>