You create a template system. You can either invent a wheel (sort of) by encoding it yourself, or simply using a weighting system such as mustache .
For a very easy approach, you can use regular expressions to formulate the syntax of your template variables. Just determine how you can write the variable, then extract the names and labels used and replace them as you wish.
The function used for this is preg_replace_callback
. The following is a small example code ( Demo ) that reflects only simple substitution, however you can change the replacement procedure to access the required values ββ(in this example I use a variable that is either Array
or implements ArrayAccess
):
<?php $template = <<<EOD This is my template, I can use [vars] at free [will]. EOD; class Template { private $template; private $vars; public function __construct($template, $vars) { $this->template = $template; $this->vars = $vars; } public function replace(array $matches) { list(, $var) = $matches; if (isset($this->vars[$var])) { return $this->vars[$var]; } return sprintf('<<undefined:%s>>', $var); } public function substituteVars() { $pattern = '~\[([a-z_]{3,})\]~'; $callback = array($this, 'replace'); return preg_replace_callback($pattern, $callback, $this->template ); } } $templ = new Template($template, array('vars' => 'variables')); echo $templ->substituteVars();
Until it looks spectacular, it simply replaces the template tags with a value. However, as already mentioned, you can now introduce a converter into a template that can resolve template tags for a value instead of using a simple array.
You indicated in your question that you want to use the _
symbol to separate from members / functions of an object. The following is a resolver class that will resolve all global variables for this notation. It shows how to handle both elements and methods and methods for moving variables. However, it does not allow $this
, but the global namespace:
class GlobalResolver implements ArrayAccess { private function resolve($offset) { $stack = explode('_', $offset); return $this->resolveOn($stack, $GLOBALS); } private function resolveOn($stack, $base) { $c = count($stack); if (!$c) return array(false, NULL); $var = array_shift($stack); $varIsset = isset($base[$var]);
This recognizer class can then be used to use some approximate values:
class Foo { public $member = 'object member'; public function func() { return 'function result'; } public function child() { $child->member = 'child member'; return $child; } } $vars = 'variables'; $foo = new Foo; $template = <<<EOD This is my template, I can use [vars] at free [foo_func] or [foo_member] and even [foo_child_member]. EOD; $templ = new Template($template, new GlobalResolver); echo $templ->substituteVars();
Watch the full demo in action .
This will require minor modifications to ultimately satisfy your needs.