回显PHP变量返回变量名,而不是变量值


Echoing PHP variables returns the variable name, not the variable value

我正在创建一个网站,在PHP函数中存储该网站的基本代码,这样我就不必一遍又一遍地编写基本代码。在我的index.php页面中,我让它调用一个名为head的函数,并传入几个变量。

这是我的代码为index.php页面:

<?php
    include "base.php";
    head("Home");
?>

包含base.php文件,其中包含函数头。

这是头函数:

<?
    function head($title) {
?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title><?="$title | BASE"?></title>
        <link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css">
        <link rel="stylesheet" type="text/css" href="css/main.css">
    </head>
</html>
<?php
    }
?>

正如你所看到的,head函数请求一个名为$title的变量,该变量在index.php中作为"Home"传入。当页面执行时,标题显示的不是Home | Base,而是<?="$title | BASE"?>。为什么呢?我需要标题显示为Home | Base,我不知道为什么它不显示像那样

您需要启用short_open_tag才能在以前的PHP版本中使用<?= $var; ?>语法(如果您使用PHP 5.4之前的版本)

当然你可以使用标准PHP语法来修改

<?="$title | BASE"?>

<?php echo "$title | BASE"; ?>

如果你使用PHP <5.4或不能设置short_open_tag启用

将$title变量放入花括号:<?= echo "{$title} | Base"; ?>或使用.连接<?= $title . " | Base"; ?>

这将解析变量值,而不是回显名称。把变量名放在引号里