PHP 当 heredoc 的字符串来自 MySQL 文本类型时,heredoc 不起作用

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

我将 heredoc 存储在 MySQL 这样的文本类型中。

Hi, $candidate.
This is $interviewer speaking.

我想像下面这样动态地使用 heredoc。 (“$mailTemplate->body”是来自上面 MySQL 文本类型的字符串。)

$candidate = 'CANDIDATE';
$interviewer = 'INTERVIEWER';

$mailBody = <<< EOM
$mailTemplate->body
EOM;

但是heredoc不起作用,变量按原样输出。

Hi, $candidate. This is $interviewer speaking.

有什么想法吗?还是不可能?

谢谢。

不,你不能这样做。 $... 在您的 $mailTemplate->body 中被视为文本。

但是你可以使用 sprintf 来实现。

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

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

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

工作example

输出

Hello World this is a test.

将字符串中的所有变量替换为 %s,并在 sprintf 中提供值作为参数。