Replacing variables with actual data I've written a class for loading a template file and replacing the variables with actual data. Please review my code and suggest improvements.

&lt;?php
/**
 * This class will helpful for variable replacement from a loaded file
 * 
 * @author V V R
 * @version 1.0
 */
class Parser {
    public $dir = "";
    public $text = "";

    /**
     * To get directory location
     * @param $dir
     */
    function __construct($dir = "home/template") {
        $this-&gt;dir = $dir;
    }

    /**
     * To load the specified file from directory
     * @param $file
     */
    function loadFile($file) {
        try {
            if (file_exists ( $this-&gt;dir . "/" . $file )) {
                $this-&gt;text = file_get_contents ( $this-&gt;dir . "/" . $file );
            } else {
                throw new Exception ( $this-&gt;dir . "/" . $file . " does not exist" );
            }
        } catch ( Exception $e ) {
            error_log ( $e-&gt;getMessage () );
            die ();
        }
    }
    /**
     * To get the text from a file
     * @return text
     */
    function getText() {
        return $this-&gt;text;
    }

    /**
     * To replace the variables
     * @param unknown_type $var
     * @param unknown_type $text
     */
    function replace($var, $text) {
        $this-&gt;text = str_replace ( "{\$$var}", $text, $this-&gt;text );
    }
}

?&gt;
Note: I'm sorry if this is completely irrelevant but I'm not entirely sure what you are trying to accomplish. If I'm way off base please let me know.

When I create a template loader I generally use output buffering with php include. This allows you to run the page as a php file without displaying its content before you are ready. The advantage to "parsing" your php files this way is that you can still run loops and functions.

This is how your loadFile method would look.

&lt;?php

function loadFile($file, array $variables = null) {
  try {
      if (file_exists ( $this-&gt;dir . "/" . $file )) {

          // start output buffering
          ob_start();

          // create variables from the key/value pairs in the array
          if( is_array($variables) ) {
              extract($variables);
          }

          include_once $this-&gt;dir . "/" . $file;

          // store the output
          $this-&gt;text = ob_get_clean();

          // $this-&gt;text = file_get_contents ( $this-&gt;dir . "/" . $file );
      } else {
          throw new Exception ( $this-&gt;dir . "/" . $file . " does not exist" );
      }
  } catch ( Exception $e ) {
      error_log ( $e-&gt;getMessage () );
      die ();
  }
}

?&gt;


As I said before, I'm not sure what kind of templates you are trying to load, but hopefully this will help.