如果变量括在双引号中,为什么会出现错误消息


Why is there an error message if the variable is encased in double quotes?

看看下面的代码

<?php
//The array is storing a blog entry in it
$entry = array ('title' => 'sample title',
        'date' => 'August 9, 2011',
        'author' => 'daNullSet',
        'body' => 'I shall become a web developer IA',);
echo "The title of the blog is ".$entry['title']."<br />";
?>

上面的代码执行得很好,但是当我在 echo 语句中与其他字符串连接时$entry['title'] 括在双引号中时,它会返回以下解析错误。

解析错误:语法错误、意外的 '' (T_ENCAPSED_AND_WHITESPACE)、第 7 行的 C:''xampp''htdocs''php-ex''test.php 中需要标识符 (T_STRING) 或变量 (T_VARIABLE) 或数字 (T_NUM_STRING

你能指导错误的原因吗?我绝对是编程新手。谢谢

为了在字符串中使用关联数组中的值,您需要使用"复杂(卷曲)语法"。实际上,这意味着您需要将其包装在 {} 中,如下所示:

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

如果您尝试直接在双引号字符串中使用"复杂"变量而不使用大括号,您将收到报告的解析错误。

非常

值得您彻底阅读整个页面,以便您知道什么是允许的,什么是不允许的。

<?php
//The array is storing a blog entry in it
$entry = array ('title' => 'sample title',
        'date' => 'August 9, 2011',
        'author' => 'daNullSet',
        'body' => 'I shall become a web developer IA');
echo "The title of the blog is '".$entry['title']."'<br />";
?>

请尝试此

希望对您有所帮助

据我所知,为什么会导致错误是因为编译器总是检查开始和结束语法,如 {}、()、"、''。当你开始一个语法时,你应该给它一个结束标记。如果我正确理解您的问题,您的问题是您想将" 添加到" 中"。您可以使用 ''" 转义编译器以将其作为语法读取。

echo "The title of the blog is '"".$entry['title']."'"<br/>";