Calling PHP Functions Within Heredoc Strings

Calling PHP functions within HEREDOC strings

I would not use HEREDOC at all for this, personally. It just doesn't make for a good "template building" system. All your HTML is locked down in a string which has several disadvantages

  • No option for WYSIWYG
  • No code completion for HTML from IDEs
  • Output (HTML) locked to logic files
  • You end up having to use hacks like what you're trying to do now to achieve more complex templating, such as looping

Get a basic template engine, or just use PHP with includes - it's why the language has the <?php and ?> delimiters.

template_file.php

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

index.php

<?php

$page_title = "This is a simple demo";

function getPageContent() {
return '<p>Hello World!</p>';
}

include('template_file.php');

Insert a function result in the middle of PHP heredoc

No, there is no better way to do it.

Heredoc string syntax behaves much like double quote string syntax. You can't put a function name as an expression inside of the double quoted string any more than you can a heredoc. So what you're doing is fine and that's how you should be doing it. The only time you can get interpolation inside of string syntax in PHP is if the value is a variable.

For example...

$foo = function() { return 'value'; };
echo <<<SOMEHEREDOC
{$foo()}
SOMEHEREDOC;
// Is the same as
echo "{$foo()}";
// Is the ssame as
$foo = 'strtoupper';
echo "{$foo('hello world')}";

The above code would output

value

value

HELLO WORLD

php call function within heredoc

You have a lot of errors in your code. $this->$month and $this->$year must be $this->month and $this->year in your case, return "(since $month of $year)";, I think, must be return "(since {$this->month} of {$this->year})";, {$time->since{1}}; may be {$time->since(1)};, and, finally, EOF; ?> - ending PHP tag must be on newline when closing heredoc:

EOF;
?>

P.S. Why are you using old, PHP4-style properties declaration?

Heredoc and special strings

I suppose you could butcher magic methods for this:

class Magic
{
public function __call($method, $args) {
// would seriously recommend checking whether `$method` exists :)
return call_user_func_array($method, $args);
}
}

$magic = new Magic;

$str = <<<EOM
Hello this should give the {$magic->time()}.
EOM;

PHP heredoc is not working when heredoc's string from MySQL text Type

No, you cant do it like this. $... in your $mailTemplate->body is treated as text.

But you can use sprintf for this.

$text = "Hello %s this is a %s.";

$valueA = 'World';
$valueB = 'test';

echo sprintf(
$text,
$valueA,
$valueB
);

Working example.

output

Hello World this is a test.

Replace all the vars in your string by %s and provide the values as parametes in sprintf.



Related Topics



Leave a reply



Submit