Question

Trying to get a simple template system working, but it seems to affect another class.

I have two PHP classes, both called in index.php:

  • HeaderData.php - class allows user to setup Header data, eg doctype, charset.
  • PageTemplates.php - class allows user to include a template file.

When I call the HeaderData class, then manually require() a template file from view (ie contains doctype, head, meta tags etc), the code from the header class works fine in the template file, outputting the objects from the header class such as Doctype etc.

However, when I try to use the PagesTemplate class to include the template file (with manual require() removed from index.php), the template file is included, but the HeaderData class no longer works in it.
Error log shows:

  • Notice: "Undefined variable varHeaderData";
  • Error: "Call to a member function PageDoctype() on a non-object";

Both the variable and function worked fine when manually require() the template file in index.php.

The code below is dev only (data checks etc to be added):

index.php:

// Use HeaderData Class
$varHeaderData = new HeaderData( 
                            array(  
                                   'PageDoctype' => '<!DOCTYPE html>',
                                   'PageCharset' => 'UTF-8', 
                                  ));

// Use PageTemplates Class
$varPageTemplate = new PageTemplates();
$varPageTemplate->LoadTemplate('template-file.php');

PageTemplates.php Class:

class PageTemplates
  {

    private $strTemplatesDir = 'view/templates/';

    public function __construct($strTemplatesDir = NULL)
      {
        if ( is_dir($strTemplatesDir) )
          {
            $this->strTemplatesDir = $strTemplatesDir;
          }
      }


    public function LoadTemplate($strTemplateFile)
      {
         {
           require_once ($this->strTemplatesDir.$strTemplateFile);
         }
      }

  }

template-file.php:

echo $varHeaderData->PageDoctype();  

The HeaderData class simply sets the object the user entered in the array with the PageDoctype() function in the class (again this works fine without the page template class)

Can someone tell me why when using the template class to require() the template file, it stops the objects from the HeaderData from working in the template-file.php?

Was it helpful?

Solution

The simplest way to do it is to pass variable in to the LoadTemplate method as an array and use extract function:

public function LoadTemplate($strTemplateFile, $vars = array())
{
    extract($vars);
    require($this->strTemplatesDir.$strTemplateFile);
}

And in the index.php

...
$varPageTemplate->LoadTemplate('template-file.php', array(
    'varHeaderData' => $varHeaderData
));

One of your errors says: "Call to a member function PageDoctype() on a non-object", so make sure that PageDoctype() method is defined in the HeaderData class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top