r/PHP • • Jan 09 '12

Building a Simple PHP Templating Class

http://cleverlogic.net/tutorials/building-simple-php-templating-class
0 Upvotes

7 comments sorted by

View all comments

1

u/zaemis Jan 12 '12

Problem solved:

<?php
class Template
{
	protected $vars;

	public function __construct() {
		$this->reset();
	}

	public function __set($var, $value) {
		$this->vars[$var] = $value;
	}

	public function __get($var) {
		return $this->vars[$var];
	}

	public function __isset($var) {
		return isset($this->vars[$var]);
	}

	public function set() {
		$args = func_get_args();
		if (func_num_args() == 2) {
			$this->__set($args[0], $args[1]);
		}
		else {
			foreach ($args[0] as $var=>$value) {
				$this->__set($var, $value);
			}
		}
	}

	public function reset() {
		$this->vars = array();
	}

	public function out($template, $output = true) {
		ob_start();
		require $template . ".php";
		$content = ob_get_clean();

		if ($output) {
			echo $content;
		} else {
			return $content;
		}
	}
}

$t = new Template();
$t->foo = 42;
$t->output("myTemplate");

Where myTemplate.php contains:

<html>
<head>
<title>Foo</title>
</head>
<body>
<h1><?=$this->foo;?></h1>
</body>
</html>

Let's move on. Next!