Hello to all! PHP has been studying for a long time, so I switched to templates. There was such a question on code optimization. I have a template and the template engine itself, as well as the main page.
Here is the template engine:
<?php class parse_class { var $vars = array(); var $template; function get_tpl($tpl_name) { if(empty($tpl_name) || !file_exists($tpl_name)) { return false; } else { $this->template = file_get_contents($tpl_name); } } function set_tpl($key,$var) { $this->vars[$key] = $var; } function tpl_parse() { foreach($this->vars as $find => $replace) { $this->template = str_replace($find, $replace, $this->template); } } } $parse = new parse_class; ?> here is the template
<html> <head> <title>{title}</title> <meta charset="utf-8"> </head> <body> {content} </body> Actually the question is: is it possible to somehow optimize the following code so as not to write the same functions many times:
$parse->set_tpl('{title}','Заголовок сайта'); $parse->set_tpl('{content}','Контент сайта'); Thank you in advance!
set_tpland transfer them totpl_parseso that it isstr_replace('{'.$find.'}', ...you know for sure that these values are parsed, so why should we create problems in the transfer of names? the second can be passed toset_tplassociative array - key value:set_tpl(['title'=>'заголовок', 'content' => 'контент']), and in the function you can run through it and put everything in$this->vars- Alexey Shimansky