php - 为什么在字符串中嵌入函数不同于变量

标签 php php-parser

我以前问过这样的问题,但这次不同,这更多是关于解析逻辑。

我之前的问题是关于如何在字符串(双引号)中嵌入一个函数,我收到了这个答案:

$date = "date";
echo "This page is under construction<br/><br/>Current Date: {$date('l jS \of F Y')}";

然后我开始想知道为什么下面这个不起作用而上面那个工作正常:

echo "This page is under construction<br/><br/>Current Date: {date('l jS \of F Y')}";

即使变量在字符串内部工作得很好,解析过程背后的逻辑如何。

我读到在 PHP 解析器 $ 符号之后,它会尝试找到合适的变量来解析和运行,并且还会用大括号分隔变量名 {}这也是我相当理解的事情。

但是为什么在为函数开发解析器引擎时似乎需要这种语法,因为一开始它对我来说没有任何意义。

基本上,为什么我需要定义一个变量来保存函数名称的字符串表示形式,如下所示:

$date = "日期";

提前致谢。

最佳答案

From the documentation :

Note:

Functions, method calls, static class variables, and class constants inside {$} work since PHP 5. However, the value accessed will be interpreted as the name of a variable in the scope in which the string is defined. Using single curly braces ({}) will not work for accessing the return values of functions or methods or the values of class constants or static class variables.

这里有一个解决这个问题的技巧:

function _expression($x) { return $x; }
$e = '_expression';

echo "This page is under construction<br/><br/>Current Date: {$e(date('l jS \of F Y'))}";

关于php - 为什么在字符串中嵌入函数不同于变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6219972/

相关文章:

php - MySQL 偶尔会返回错误的值

PHP、Postgres 帮助使用 RETURNING

javascript - 为什么php ajax没有给出任何响应?

PHP MySQL - 无法回显 'TEXT' 值

php - Mysql选择不同的ID并只选择第一行

javascript - Markdown - PHP 解析器

php - 是否可以使用 PEG 解析 PHP?

php - 如何比较两个不包括 protected 属性的节点? (PHP-解析器)

parser-generator - PEG 语法和解析器生成器的局限性?