Calling PHP functions within HEREDOC strings -


in php, heredoc string declarations useful outputting block of html. can have parse in variables prefixing them $, more complicated syntax (like $var[2][3]), have put expression inside {} braces.

in php 5, is possible make function calls within {} braces inside heredoc string, have go through bit of work. function name has stored in variable, , have call dynamically-named function. example:

$fn = 'testfunction'; function testfunction() { return 'ok'; } $string = <<< heredoc plain text , function: {$fn()} heredoc; 

as can see, bit more messy just:

$string = <<< heredoc plain text , function: {testfunction()} heredoc; 

there other ways besides first code example, such breaking out of heredoc call function, or reversing issue , doing like:

?> <!-- directly output html , breaking php function --> plain text , function: <?php print testfunction(); ?> 

the latter has disadvantage output directly put output stream (unless i'm using output buffering), might not want.

so, essence of question is: there more elegant way approach this?

edit based on responses: seem kind of template engine make life easier, require me invert usual php style. not that's bad thing, explains inertia.. i'm figuring out ways make life easier though, i'm looking templates now.

i not use heredoc @ this, personally. doesn't make "template building" system. html locked down in string has several disadvantages

  • no option wysiwyg
  • no code completion html ides
  • output (html) locked logic files
  • you end having use hacks you're trying achieve more complex templating, such looping

get basic template engine, or use php includes - it's why language has <?php , ?> delimiters.

template_file.php

<html> <head>   <title><?php echo $page_title; ?></title> </head> <body>   <?php echo getpagecontent(); ?> </body> 

index.php

<?php  $page_title = "this simple demo";  function getpagecontent() {     return '<p>hello world!</p>'; }  include('template_file.php'); 

Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -