如何将参数传递给包含的文件?

2022-08-30 10:38:26

我试图使整个部分成为自己的包含文件。一个缺点是标题和描述以及关键字将是相同的;我不知道如何将参数传递给包含文件。<head>

所以这是代码:

索引.php

<?php include("header.php?header=aaaaaaaaaaaaaaaaaaaaa"); ?>

<body>
.....
..
.

页眉.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<link rel="shortcut icon" href="favicon.ico">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="Keywords" content=" <?php $_GET["header"]?> " >
<meta name="Description" content=" <?php $_GET["header"]?> " >
<title> <?php $_GET["header"]?> </title>
<link rel="stylesheet" type="text/css" href="reset.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
</head>

显然这不起作用;如何将参数传递给包含的文件?


答案 1

包含具有从中调用它的行的范围。

如果不想创建新的全局变量,可以使用函数进行包装:include()

function includeHeader($title) {
    include("inc/header.php");
}

$title将在包含的代码中定义,每当您使用值调用时,例如 .includeHeaderincludeHeader('My Fancy Title')

如果要传递多个变量,则始终可以传递数组而不是字符串。

让我们创建一个泛型函数:

function includeFile($file, $variables) {
    include($file);
}

瞧!

使用数据提取使它更加整洁:

function includeFileWithVariables($fileName, $variables) {
   extract($variables);
   include($fileName);
}

现在,您可以执行以下操作:

includeFileWithVariables("header.php", array(
    'keywords'=> "Potato, Tomato, Toothpaste",
    'title'=> "Hello World"
));

知道它将导致变量并在所包含代码的范围内定义。$keywords$title


答案 2

索引.php:

<?php
$my_header = 'aaaaaaaaaaaaaaaaaaaa';
include 'header.php';
?>

和标头.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="shortcut icon" href="favicon.ico" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="Keywords" content=" <?php echo $my_header ?> " />
<meta name="Description" content=" <?php echo $my_header ?> " />
<title> <?php echo $my_header ?> </title>
<link rel="stylesheet" type="text/css" href="reset.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
</head>

这不是一个理想的解决方案,但我明白这是你在php中的第一步。

您的文档类型与代码不匹配。我已将您的标题html调整为XHTML。


推荐