2012-08-10 74 views
0

看一下下面的代碼:爲什麼複雜的語法會給出錯誤?

<?php 
//The array stores the nodes of a blog entry 
$entry = array('title' => "My First Blog Entry", 
     'author' => "daNullSet", 
     'date' => "August 10, 2012", 
     'body' => "This is the bosy of the blog"); 
echo "The title of the blog entry is ".{$entry['title']}; 
?> 

它提供了以下錯誤我。

Parse error: syntax error, unexpected '{' in C:\xampp\htdocs\php-blog\simple-blog\array-test.php on line 7

如果我在上面的代碼中刪除在echo語句中引入複雜語法的大括號,則錯誤消失。請幫我調試上面的代碼。 謝謝!

回答

4

刪除大括號,它會正常工作。這種行爲不是一個錯誤,而是你的語法不正確。簡而言之,在雙引號或者heredoc中使用花括號來進行復雜的變量插值,而不是在外部。

更詳細的解釋:

使用此:

echo "The title of the blog entry is ".$entry['title']; 

複雜的變量(和花括號內的表達式的插值),特別是中包含雙引號的字符串或here文檔,其中需要正確插值工作,並在那裏可能會出現歧義。這是一種乾淨的語法,因此不會造成歧義,這意味着不需要消歧。

簽出更多的複雜變數的位置:http://php.net/manual/en/language.types.string.php

如果你是封閉的雙引號內的數組的值,可以使用大括號能進行正確的變量代換。但是,這很好,大多數人應該能夠完美地閱讀並理解你在做什麼。您正在使用{錯誤的方式

使用

1

要麼

echo "The title of the blog entry is ".$entry['title']; 

OR

echo "The title of the blog entry is ". $entry{title}; 

即使你需要連接字符串。你可以寫在心裏""

echo "The title of the blog entry is $entry{title}"; 

Working DEMO

Complex (curly) syntax

+0

爲什麼是得到downvoted? – 2012-08-10 06:29:41

+0

有禮貌地提及downvote的原因。 – diEcho 2012-08-10 06:31:00

+0

我沒投你一票,但顯然你的第二個代碼會產生'注意:使用未定義的常量標題 - 假設'標題'在' – Baba 2012-08-10 06:32:42

1
echo "The title of the blog entry is " . $entry['title']; 
1

我想你要使用正確的語法是這樣的

echo "The title of the blog entry is {$entry['title']}"; 
1

的正確方法使用}是:

echo "The title of the blog entry is {$entry['title']}"; 

您可以也只是用:

echo "The title of the blog entry is " . $entry['title']; 
相關問題