基于php双引号中访问数组元素报错的解决方法
最近在做微信公家号开拓,在一个发送图文接口中,必要把数组元素拼接在XML字符串中 $value){ $items .= "功效竟报如下错误信息:从错误信息看是单引号的题目,坚决去掉之后就没报错了。然而我就抑郁了,引用下标为字符串的数组元素莫非不应加引号吗?到php官方手册去查了关于数组的描写,有一段是这样的: 'apple','veggie' => 'carrot'); // 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']";这里给出了两种错误的写法,当一个平凡数组变量或超全局数组变量包括在双引号中时,引用索引为字符串的数组元素,索引字符串不该该再添加单引号。那正确的写法是奈何的呢?于是我继承查找官方手册,找到如下说法: 'apple','veggie' => 'carrot');// This defines a constant to demonstrate what's going on. The value 'veggie' // The following is okay,as it's inside a string. Constants are not looked for// within strings,so no E_NOTICE occurs hereprint "Hello $arr[fruit]"; // Hello apple// With one exception: braces surrounding arrays within strings allows constants// to be interpretedprint "Hello {$arr[fruit]}"; // Hello carrotprint "Hello {$arr['fruit']}"; // Hello apple $arr = array('fruit' => 'apple',as it's inside a string. Constants are not looked for // With one exception: braces surrounding arrays within strings allows constants 这里给出了三种正确的写法:第一种写法索引字符串不添加任何引号,此时暗示获取索引为字符串fruit的数组元素,输出apple。 第二种写法索引字符串也没有添加任何引号,同时将数组变量用一对花括号{ }给包了起来,此时fruit现实上暗示一个常量,而不是一个字符串,因此暗示获取索引为fruit常量值的数组元素,常量fruit的值是veggie,以是输出carrot。 第三种写法是引用字符串不单添加了单引号,同时也将数组变量用一对花括号{ }给包了起来,此时暗示获取索引为字符串fruit的数组元素,输出apple。 其后我继承查找,发明这样一段代码: print $arr['fruit']; // apple
在正常环境下,数组变量没有被双引号困绕时,是否给索引字符串加上单引号输出功效都同等时apple,可是当界说一个与索引字符串fruit同名的常量时,未加单引号的索引字符串输出功效就成了carrot,而加上单引号照旧apple。 结论:1. 数组变量未用双引号包罗时, (1) 索引字符串加单引号暗示字符串自己 (2)索引字符串未加单引号暗示常量,当常量未界说时则理会为字符串,等效于加上单引号。 2. 数组变量用双引号包罗时, (1) 索引字符串不加单引号暗示字符串自己 (2) 数组变量加上花括号暗示与字符串同名常量 (3) 索引字符串加上单引号且数组变量加上花括号暗示字符串自己
附:php手册数组声名URL http://php.net/manual/zh/language.types.array.php 以上这篇基于php双引号中会见数组元素报错的办理要领就是小编分享给各人的所有内容了,但愿能给各人一个参考,也但愿各人多多支持编程之家。 (编辑:湖南网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |