Cookie Consent by Free Privacy Policy Generator

Create a PHP template class for handling header and footer templates

Create a PHP template class for handling header and footer templates that will make your code more organised and maintainable.

This approach is more flexible, and it allows you to add more methods and properties to your Template class as needed.

Here's an example:

PHP:
class Template {
    private $documentRoot;
   
    public function __construct() {
        $this->documentRoot = $_SERVER['DOCUMENT_ROOT'];
    }

    public function header() {
        include $this->documentRoot . "/includes/header.php";
    }

    public function footer() {
        include $this->documentRoot . "/includes/footer.php";
    }
}

To use this class, you can instantiate it and call the methods like this:
PHP:
$template = new Template();

$template->header();

// Your page content goes here

$template->footer();

Previously, I had been using this approach:
PHP:
<?php
 // header
function pf_Header() {

  include $_SERVER['DOCUMENT_ROOT']."/includes/header.php";

}

 // footer
function pf_Footer() {

  include $_SERVER['DOCUMENT_ROOT']."/includes/footer.php";

}
?>
 
Back
Top