为什么复杂的语法会出错?

时间:2012-08-10 06:25:45

标签: php

请看下面的代码:

<?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']};
?>

它给我发出以下错误。

  

解析错误:语法错误,第7行的C:\ xampp \ htdocs \ php-blog \ simple-blog \ array-test.php中的意外“{”

如果我在上面的代码中删除引入echo语句中的复杂语法的大括号,则错误消失了。请帮我调试上面的代码。 谢谢!

5 个答案:

答案 0 :(得分:4)

删除花括号,它会正常工作。这种行为不是错误,而是您的语法不正确。简而言之,使用花括号进行复杂变量插值可以在双引号内或在heredoc中使用,而不是在外部。

更详细的解释:

使用此:

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

复杂变量(以及花括号内的表达式的插值)专门用于WITHIN双引号字符串或heredocs,其中需要正确的插值,并且可能出现歧义。这是一个干净的语法,因此不会产生歧义,这意味着不需要消除歧义。

在此处查看有关复杂变量的更多信息:http://php.net/manual/en/language.types.string.php

如果将数组值括在双引号内,则可以使用花括号来允许正确的变量插值。但是,这很好用,大多数人应该能够完美地阅读这些并理解你在做什么。

答案 1 :(得分: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

答案 2 :(得分:1)

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

答案 3 :(得分:1)

我认为你想要使用的正确语法是这样的

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

答案 4 :(得分:1)

使用}的正确方法是:

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

您也可以使用:

echo "The title of the blog entry is " . $entry['title'];
相关问题