“贪婪令牌解析”在PHP [英] 'Greedy Token Parsing' in PHP

查看:72
本文介绍了“贪婪令牌解析”在PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP中的Greedy token parsing是什么?
我在Codeigniter指南中发现了这一点:



总是使用单引号字符串,除非你需要变量解析,如果你需要变量解析,使用大括号



我的字符串{$ foo}


解决方案

贪心标记解析指的是这样的:

  $ fruit =apple 
$ amount = 3;
$ string =我有$ amount $ fruits;

可能的预期输出:我有3个苹果

实际输出:我有3



当然,这是一个初学者的错误,但即使专家有时也犯错误!



就个人而言,我不喜欢内插变量的所有,大括号或不。我发现我的代码更容易阅读,像这样:

  $ string =I have。$ amount。。 。s; 

请注意,代码编辑器可以更方便地对此行进行颜色编码,如Notepad ++中所示: / p>



再次,有些人可能更喜欢让引擎做内插:

  $ string = sprintf %d%ss,$ amount,$ fruit); 

这完全取决于个人喜好,但你引用的指南中的要点是小心您正在写的内容。


What is 'Greedy token parsing' in PHP ? I found this in Codeigniter guideline:

"Always use single quoted strings unless you need variables parsed, and in cases where you do need variables parsed, use braces to prevent greedy token parsing."

"My string {$foo}"

An answer with good explanation will help.

Thanks !!

解决方案

Greedy token parsing refers to something like this:

$fruit = "apple";
$amount = 3;
$string = "I have $amount $fruits";

Possible expected output: "I have 3 apples"
Actual output: "I have 3 "

Of course, this is a beginner mistake, but even experts make mistakes sometimes!

Personally, I don't like to interpolate variables at all, braces or not. I find my code much more readable like this:

$string = "I have ".$amount." ".$fruit."s";

Note that code editors have an easier job colour-coding this line, as shown here in Notepad++:

Then again, some people might prefer letting the engine do the interpolation:

$string = sprintf("I have %d %ss",$amount,$fruit);

It's all up to personal preference really, but the point made in the guideline you quoted is to be careful of what you are writing.

这篇关于“贪婪令牌解析”在PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆