代码
$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)
1
fahai 2017-11-27 23:01:36 +08:00
$dsn = "HOST is {$conn['host']}";
|
2
xiaoyanbot OP |
3
xinlai 2017-11-27 23:05:54 +08:00
$dsn="HOST is ".$conn['host'];
|
4
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 秒 |
6
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']"; |
7
cxbig 2017-11-28 05:12:28 +08:00
这个案例我会写成:
echo 'HOST is ', $conn['host']; - 用逗号连接,不拼接字符串,也不用双引号解析变量。省资源。 |
8
konakona 2017-11-28 05:19:41 +08:00
因为你用的是数组,如果只是一个变量,则不会报错。
数组的话记得用花括号包。 |
9
R18 2017-11-28 06:48:45 +08:00 via Android
这涉及到的是 PHP 中的变量解析 参见变量解析,复杂语法 http://php.net/manual/zh/language.types.string.php#language.types.string.parsing
|
10
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'....` |
11
GreatHumorist 2017-11-28 09:10:29 +08:00
用单引号不会出错,但是在双引号里使用下标引用数组元素必须加{}来区分,不然会产生解析出错
|
12
LeungJZ 2017-11-28 09:13:58 +08:00
要不
$dsn = "HOST is {$conn['host']}"; 要不 $dsn = "HOST is $conn[host]"; 在双引号里面访问数组数据可以不加单引号。 |