开发者

Why embedding functions inside of strings is different than variables

I've asked a question like this before but this one is different, this is more about parsing logic.

My previous questions was about how to embed a function inside of a string (double-quoted) and I received this answer:

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

And after that I started to wonder why this one below is not working while the the one above is working fine:

echo "This page is under construction<br/><br/>Current D开发者_运维百科ate: {date('l jS \of F Y')}";

How is the logic behind the parsing process even though variables are working pretty fine inside of the strings.

I read that after PHP parser $ sign, it tries to find appropriate variable to parse and run and also to delimit the variable name we also use curly braces {} and that is also something I understand fairly.

But why this kind of syntax is seemed required while developing the parser engine for functions because at first it didn't make any sense to me.

Basically, why do I need to define a variable which hold string representaion of the function name such as below:

$date = "date";

Thanks in advance.


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.

Here is a hack around this though:

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

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


The reason is simple. The syntax for any complex parsing in double quotes to occur is {$. No other byte sequence will trigger this behaviour in PHP. That syntax token is know as T_CURLY_OPEN.

And that you can use functions with that is only a by-product of PHP supporting object and array expressions with it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜