2011-01-19 61 views
36

的(双引号字符串)当内插PHP的字符串索引数组元素(5.3.3的Win32) 以下行为可预期或不:插值关联数组在PHP

$ha = array('key1' => 'Hello to me'); 

print $ha['key1']; # correct (usual way) 
print $ha[key1];  # Warning, works (use of undefined constant) 

print "He said {$ha['key1']}"; # correct (usual way) 
print "He said {$ha[key1]}"; # Warning, works (use of undefined constant) 

print "He said $ha['key1']"; # Error, unexpected T_ENCAPSED_AND_WHITESPACE 
print "He said $ha[ key1 ]"; # Error, unexpected T_ENCAPSED_AND_WHITESPACE 
print "He said $ha[key1]";  # !! correct (How Comes?) 

Inerestingly,的最后一行似乎是正确的PHP代码。任何解释? 此功能可信吗?


编辑:现在 粗体,以减少误解设置张贴的点。

回答

38

是的,你可以信任它。 All ways of interpolation a variable are covered in the documentation相当不错。

如果你想有一个理由为什么这样做,那么,我不能帮你在那里。但是一如既往:PHP是老的并且已经发展了很多,因此引入了不一致的语法。

+0

@nikic真的很有用,我不能在这个文档中找到这个确切的情况下(W/O大括号),它在哪里?谢谢,rbo – 2011-01-19 18:11:59

+0

@mario:就我个人而言,我认为这不太好,但很多人可能还有其他方面的问题 - >丢掉了那部分。 – NikiC 2011-01-19 18:12:24

+0

@橡胶靴:注意这一行:`echo“他喝了一些果汁[koolaid1]果汁。”。PHP_EOL;`。 – NikiC 2011-01-19 18:13:03

8

最后一个是由PHP标记器处理的特殊情况。它不会查找是否定义了通过该名称定义的任何常量,它始终假定字符串文字与PHP3和PHP4兼容。

9

是的,这是明确定义的行为,并且将始终查找字符串键'key',而不是(可能未定义的)常量key的值。

例如,请考虑下面的代码:

$arr = array('key' => 'val'); 
define('key', 'defined constant'); 
echo "\$arr[key] within string is: $arr[key]"; 

这将输出如下:

$arr[key] within string is: val 

这就是说,它可能写出这样的代码不是最好的做法,而是要么使用:

$string = "foo {$arr['key']}" 

$string = 'foo ' . $arr['key'] 

语法。

0

要回答你的问题,是的,是的,它可以了,就像破灭和爆炸,PHP是非常非常宽容...所以矛盾比比皆是

我不得不说,我喜欢PHP的插值basical菊花冲孔变量转换为字符串然后在那里,

但是,如果您只使用单个数组的对象进行字符串变量插值,则可能更容易编写一个模板,您可以将雏菊打印特定对象变量(比如说javascript或python ),并因此明确地控制应用于字符串的变量范围和对象

我以为这家伙的isprintf对这种事情

http://www.frenck.nl/2013/06/string-interpolation-in-php.html

<?php 

$values = array(
    'who' => 'me honey and me', 
    'where' => 'Underneath the mango tree', 
    'what' => 'moon', 
); 

echo isprintf('%(where)s, %(who)s can watch for the %(what)s', $values); 

// Outputs: Underneath the mango tree, me honey and me can watch for the moon