2012-08-10 70 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']; 
相关问题