Return to Snippet

Revision: 66703
at June 20, 2014 09:02 by Queue


Initial Code
// anonymous function
$echo = function($param) {

  return $param;
};

$test = <<<HEREDOC
\$echo is now a generic function that can be used in all sorts of ways:
Output the result of a function: {$echo(date('r'))}
Output the value of a constant: {$echo(__FILE__)}
Static methods work just as well: {$echo(MyClass::getSomething())}
2 + 2 equals {$echo(2+2)}
HEREDOC;

echo $echo(test);

// The same works not only with HEREDOC strings,
// but with double-quoted strings as well:
$string = "{$echo(2+2)}";
echo $echo($string);

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

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

Initial Title
Using functions / expressions in HEREDOC strings

Initial Tags
php, function

Initial Language
PHP