manngo Posted July 16, 2010 Share Posted July 16, 2010 I have 3 main methods: The first is to use the PHP eval() function, together with a constructed Heredoc. The second is to use str_replace() over an array of variables. This has the advantage of allowing me to use my own notation for variables. The third is similar, except that it begins by reading what variables in the template are required. Below is some sample code (first two methods only). I like the first because it is very simple. The question is, can anybody see any problems with either approach? Thanks, Mark <?php // Test File test.txt contains: // $a plus $b gives $c etc // $file=file_get_contents('test.txt'); // For testing, hard code: $file=$file2='$a plus $b gives $c etc'; // Dummy data $a=1; $b=2; $c=3; // Template file can now be interpolated // in a number of ways // Method 1: use eval and constructed Heredoc eval("\$file=<<<END\n$file\nEND;\n"); print $file; // Method 2: use str_replace and $variables array // ($variables will default to $GLOBALS, but can // be any array of variable names); // This will read from available variables into // the string. function interpolate2($text,$variables=null) { $variables=$variables ? $variables : $GLOBALS; foreach($variables as $variable=>$value) if(strstr($text,"\$$variable")) $string=str_replace("\$$variable",$value,$text); return $text; } print interpolate2($file2); ?> Quote Link to comment https://forums.phpfreaks.com/topic/207915-templates-string-interpolation/ Share on other sites More sharing options...
Alex Posted July 16, 2010 Share Posted July 16, 2010 The problem with the first method is that you're using eval. The standard is "Eval is evil", just Google it and you'll find plenty of articles explaining exactly why you shouldn't use eval. With your second method there are a few things I'd do a bit differently. My first issue is with this line: $variables=$variables ? $variables : $GLOBALS; Although null does evaluate to false you should use a function like isset instead. My other issue with the code is that there's no need to check to see if the variable exists in the string before you attempt to replace it. If it does not exist and you try to replace it simply won't be replaced (obviously). $variables = isset($variables) ? $variables : $GLOBALS; Quote Link to comment https://forums.phpfreaks.com/topic/207915-templates-string-interpolation/#findComment-1086912 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.