关于PHP CLI 代码的引号使用建议

-r or --run : This runs a line of PHP code supplied as the argument, rather than executing it from a file. The line of code should be enclosed by single quotes because shells like bash will try to interpolate PHP variables as if they were shell variables if you use double quotes. This performs a similar role to the -a interactive mode, except that PHP’s “state” is cleared after each line is executed. This means that the line of code supplied is treated as the whole script to be executed, and execution is terminated once it has been run. Here’s an example that will print out "4" followed by a new line character:

~$ php -r "echo (2+2).\"\n\";"



Note that the line must be well-formed syntactically correct PHP,so don’t miss the semicolon at the end! I will return to -r later in this chapter in the section "The Many Ways to Call PHP Scripts."


在shell脚本里使用php时,如果php没有使用变量,命令行下面的代码用单引号还是双引号没有区别,但是用到了php变量,比如下面例子中的$argi和$argn,因为shell变量使用方式跟PHP相同——双引号里的变量可以使用,单引号里的变量当字符串处理,所以在执行时这两个变量是shell变量而shell脚本并没有定义这两个变量,从而导致无值得情况出现;


反过来验证:



示例:

红色为原代码(N),绿色为修改后的代码(Y)

~$ more my_text_file.txt | php -B "echo \"Lets add line numbers...\n\";" -R "echo \"$argi: $argn\n\";" -E "echo \"That's the end folks\n\";"

~$ more my_text_file.txt | php -B "echo \"Lets add line numbers...\n\";" -R 'echo "$argi: $argn\n";' -E "echo \"That's the end folks\n\";" 



评论0条