Skip to content

Instantly share code, notes, and snippets.

@mulhoon
Last active February 18, 2018 22:18
Show Gist options
  • Save mulhoon/0fdf074223353c1752d9 to your computer and use it in GitHub Desktop.
Save mulhoon/0fdf074223353c1752d9 to your computer and use it in GitHub Desktop.
Simple PHP Template engine
<?php
/*
Original by Rasmus Larsson
http://www.rasmuslarsson.se/2013/05/a-template-engine-in-php/
*/
class Template
{
protected $template;
protected $variables = array();
public function __construct($template)
{
$this->template = $template;
}
public function __get($key)
{
return $this->variables[$key];
}
public function __set($key, $value)
{
$this->variables[$key] = $value;
}
public function __toString()
{
extract($this->variables);
chdir(dirname($this->template));
ob_start();
include basename($this->template);
return ob_get_clean();
}
}
/* Usage:
require 'templateEngine.php';
$message = new Template("templates/template1.html");
$message->username = $username;
echo $message;
// in your template use...
<?= $username ?>
*/
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment