在 INI 文件中使用关键字作为变量名
我在 INI 文件中有以下内容:
[country]
SE = Sweden
NO = Norway
FI = Finland
但是,当 var_dump()ing PHP 的 parse_ini_file() 函数时,我得到以下输出:
PHP Warning: syntax error, unexpected BOOL_FALSE in test.ini on line 2
in /Users/andrew/sandbox/test.php on line 1
bool(false)
看来“NO”被保留。还有其他方法可以设置名为“NO”的变量吗?
I have the following in an INI file:
[country]
SE = Sweden
NO = Norway
FI = Finland
However, when var_dump()ing PHP's parse_ini_file() function, I get the following output:
PHP Warning: syntax error, unexpected BOOL_FALSE in test.ini on line 2
in /Users/andrew/sandbox/test.php on line 1
bool(false)
It appears that "NO" is reserved. Is there any other way I can set a variable named "NO"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
另一个技巧是用它们的值反转你的ini键并使用 array_flip:
仍然需要在 NO 周围使用引号(至少),如果这样做,
您不会收到错误,但 $countries["NO"] 的值将是一个空字符串。
Another hack would be to reverse your ini keys with their values and use array_flip:
Still you will need to use quotes around NO (at least), if you do
you don't get an error but value for $countries["NO"] will be an empty string.
这可能来得有点晚了,但是 PHP 的 parse_ini_file 的工作方式让我非常困扰,以至于我编写了自己的小解析器。
请随意使用它,但请小心使用它仅经过了浅层测试!
它有什么不同?变量名称只能由字母数字字符组成,但除此之外没有任何限制。字符串必须用 " 封装,其他所有内容都必须是特殊值,例如
no
、yes
、true
、false
、on
、off
、null
或none
有关映射,请参阅代码。This propably comes a little late but the way PHPs parse_ini_file works bothered me so much that I wrote my own little parser.
Feel free to use it, but use with care it has only been shallowly tested!
What does it differently? Variable names may only consist of alphanumerical characters but other than that no restrictions to them. Strings must be encapsulated with " everything else has to be a special value like
no
,yes
,true
,false
,on
,off
,null
ornone
. For mapping see code.有点黑客,但您可以在键名称周围添加反引号:
然后像这样访问它们:
输出:
Kind of a hack but you can add backticks around the key names:
Then access them like so:
Output:
我遇到了同样的问题,并试图以各种可能的方式逃避这个名字。
然后我想起,由于 INI 语法,名称和值都会被修剪,因此以下解决方法可能应该可以解决问题:
并且它有效;)只要您的同事阅读注释(情况并非总是如此)并且不要意外删除它。所以,是的,数组翻转解决方案是一个安全的选择。
I ran into the same problem and tried to escape the name in every possible way.
Then I remembered that because of the INI syntax both names and values will be trimmed, so the following workaround MAYBE should do the trick:
And it works ;) As long as your co-workers read the comments (which is not always the case) and don't delete it accidentally. So, yes, the array flipping solution is a safe bet.
当字符串中存在单引号组合(例如 't 或 's)时,我收到此错误。为了解决这个问题,我将字符串用双引号括起来:
之前:
之后:
I was getting this error when there were single quote combinations in the string such as 't or 's. To get rid of the problem, I wrapped the string in double quotes:
Before:
After:
从
parse_ini_file
的手册页:所以不,你不能设置变量
NO
。From the manual page for
parse_ini_file
:So no, you can't set a variable
NO
.