Posted By

Queue on 06/20/14


Tagged

php function heredoc Anonymous


Versions (?)

Using functions / expressions in HEREDOC strings


 / Published in: PHP
 

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

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

  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);

Report this snippet  

You need to login to post a comment.