Using functions / expressions in HEREDOC strings


/ Published in: PHP
Save to your folder(s)

use anonymous function that returns parameter passed to it to evaluate functions, constants, and expressions in HEREDOC


Copy this code and paste it in your HTML
  1. // anonymous function
  2. $echo = function($param) {
  3.  
  4. return $param;
  5. };
  6.  
  7. $test = <<<HEREDOC
  8. \$echo is now a generic function that can be used in all sorts of ways:
  9. Output the result of a function: {$echo(date('r'))}
  10. Output the value of a constant: {$echo(__FILE__)}
  11. Static methods work just as well: {$echo(MyClass::getSomething())}
  12. 2 + 2 equals {$echo(2+2)}
  13. HEREDOC;
  14.  
  15. echo $echo(test);
  16.  
  17. // The same works not only with HEREDOC strings,
  18. // but with double-quoted strings as well:
  19. $string = "{$echo(2+2)}";
  20. echo $echo($string);

URL: blog.nazdrave.net/?p=626

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.