PHP 双引号里用单引号会报错? 我记得不会呀,为啥现在会了?

2017-11-27 22:56:51 +08:00
 xiaoyanbot

代码


$conn['host'] = '127';

$dsn = "HOST is $conn['host']";

echo $dsn;

报错信息:

Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING)

3186 次点击
所在节点    PHP
12 条回复
fahai
2017-11-27 23:01:36 +08:00
$dsn = "HOST is {$conn['host']}";
xiaoyanbot
2017-11-27 23:05:25 +08:00
@fahai

数组引用, $conn['host'] 和 $conn[host] 效率会差多少?
xinlai
2017-11-27 23:05:54 +08:00
$dsn="HOST is ".$conn['host'];
Zephyros
2017-11-27 23:55:33 +08:00
<?php
$conn['host'] = '127';

$t0 = microtime(1);

for ($i=0; $i < 9999999; $i++) {
$dsn = "HOST is {$conn['host']}";
}
$t1 = microtime(1);
echo ($t1 - $t0); //1.0226299762726 秒
echo "\n";

for ($i=0; $i < 9999999; $i++) {
$dsn = "HOST is $conn[host]";
}

$t2 = microtime(1);
echo ($t2 - $t1); //1.0196290016174 秒
xfspace
2017-11-28 00:10:55 +08:00
@xinlai PHP 双引号内可以用$,单引号则不行。Feature
580a388da131
2017-11-28 00:28:25 +08:00
查手册是好习惯 手册里写有哇
http://www.php.net/manual/zh/language.types.array.php

// With one exception: braces surrounding arrays within strings allows constants
// to be interpreted
print "Hello {$arr[fruit]}"; // Hello carrot
print "Hello {$arr['fruit']}"; // Hello apple

// This will not work, and will result in a parse error, such as:
// Parse error: parse error, expecting T_STRING' or T_VARIABLE' or T_NUM_STRING'
// This of course applies to using superglobals in strings as well
print "Hello $arr['fruit']";
print "Hello $_GET['foo']";
cxbig
2017-11-28 05:12:28 +08:00
这个案例我会写成:

echo 'HOST is ', $conn['host'];

- 用逗号连接,不拼接字符串,也不用双引号解析变量。省资源。
konakona
2017-11-28 05:19:41 +08:00
因为你用的是数组,如果只是一个变量,则不会报错。
数组的话记得用花括号包。
R18
2017-11-28 06:48:45 +08:00
这涉及到的是 PHP 中的变量解析 参见变量解析,复杂语法 http://php.net/manual/zh/language.types.string.php#language.types.string.parsing
klgd
2017-11-28 08:51:06 +08:00
@xiaoyanbot #2 $conn['host'] 和 $conn[host]根本不是同一个东西
不带引号,host 表示一个常量,PHP 会先去找这个常量,如果有就用其值作为键值,如果没有就把 host 看作字符串直接作为键值,并报出一个 Notice

`Notice: Use of undefined constant host - assumed 'host'....`
GreatHumorist
2017-11-28 09:10:29 +08:00
用单引号不会出错,但是在双引号里使用下标引用数组元素必须加{}来区分,不然会产生解析出错
LeungJZ
2017-11-28 09:13:58 +08:00
要不
$dsn = "HOST is {$conn['host']}";
要不
$dsn = "HOST is $conn[host]";
在双引号里面访问数组数据可以不加单引号。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/410052

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX