看看下面的代码:
<?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']};
?>
它给我以下错误。
解析错误:语法错误,C:''xampp''htdocs''php-blog''simple-blog''array-test.php 第 7 行中意外的"{"
如果我删除大括号,在上面的代码中引入 echo 语句中的复杂语法,错误就会消失。请帮我调试上面的代码。谢谢!
去掉大括号,它会正常工作。此行为不是错误,而是您的语法不正确。简而言之,使用大括号进行复杂变量插值在双引号内或 heredoc 中工作,而不是在外部。
更详细的解释:
使用这个:
echo "The title of the blog entry is ".$entry['title'];
复杂变量(以及大括号内的表达式插值)专门在双引号字符串或 heredocs 中工作,其中需要正确的插值,并且可能发生歧义。这是一段干净的语法,因此不会导致歧义,这意味着不需要消除歧义。
在此处查看有关复杂变量的更多信息:http://php.net/manual/en/language.types.string.php
如果要将数组值括在双引号内,则可以使用大括号来允许正确的变量插值。但是,这很好用,大多数人应该能够完美地阅读并理解您在做什么。
echo "The title of the blog entry is " . $entry['title'];
我认为您要使用的正确语法是这样的
echo "The title of the blog entry is {$entry['title']}";
使用}
的正确方法是:
echo "The title of the blog entry is {$entry['title']}";
您也可以只使用:
echo "The title of the blog entry is " . $entry['title'];
你用错{
方式
用 也
echo "The title of the blog entry is ".$entry['title'];
或
echo "The title of the blog entry is ". $entry{title};
即使你需要连接字符串。 您可以在""
内编写所有内容
echo "The title of the blog entry is $entry{title}";
工作演示
阅读Complex (curly) syntax