Skip to content

Instantly share code, notes, and snippets.

@nezarfadle
Last active May 26, 2017 08:43
Show Gist options
  • Save nezarfadle/c49b6d3df44a454737de141d15e60d9a to your computer and use it in GitHub Desktop.
Save nezarfadle/c49b6d3df44a454737de141d15e60d9a to your computer and use it in GitHub Desktop.
How to use PHP Closure to write a simple template engine

File: index.php

class Article
{
    private $title = "This is an article";
}

class Post
{
    private $title = "This is a post";
}

class Template
{

    function render($context, $tpl)
    {

        $closure = function($tpl)
        {
            ob_start();
            include $tpl;
            return ob_end_flush();
        };

        $closure = $closure->bindTo($context, $context);
        $closure($tpl);

    }

}

$article = new Article();
$post = new Post();
$template = new Template();

$template->render($article, 'tpl.php');
$template->render($post, 'tpl.php');

File: tpl.php

<h1><?php echo $this->title;?></h1>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment