2011-01-19 60 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