所以今天我遇到了这个功能/错误,我正在努力绕过正在发生的事情。
所以我们都知道在php中这个:
echo 'hello';
print 'world';
echo gettype('test');
将返回此信息:
hello
world
string
然而,直到今天我才意识到这一点:
echo hello;
print world;
echo gettype(hello);
将返回此信息:
hello
world
string
这里发生了什么?在php的编译过程中发生了什么,它将任何单个单词视为字符串?这有名字吗?它有什么用处吗?
答案 0 :(得分:7)
如果PHP无法通过hello
的名称找到函数或常量,那么是的,它会将其视为字符串。然而,这是不好的做法,甚至被警告:
>php -r 'error_reporting(E_ALL|E_STRICT);echo gettype(blah);'
PHP Notice: Use of undefined constant blah - assumed 'blah' in Command line code on line 1
所以,故事的寓意是始终在PHP中启用error_reporting
(就像你应该总是 use strict
和{{ 1}}在Perl中。
答案 1 :(得分:4)
如果你没有在引号内包裹一段“字符串”(无论是双引号还是单引号),解释器将尝试进行猜测并将其转换为字符串。我相信当你在error_reporting(E_ALL)中运行那段PHP时,你会看到一个通知
Notice: Use of undefined constant string - assumed 'string' in Command line code on line 1
一个好的做法是在开发设置中始终打开error_reporting到E_ALL,但是记得在生产中把它变成描述性较差的,如果你的php错误,你不希望人们有权访问敏感信息(例如路径)进行。