php 如何将参数传递给包含的文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4315271/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pass arguments to an included file?
提问by menardmam
I'm trying to make the whole <head>
section its own include file. One drawback is the title and description and keyword will be the same; I can't figure out how to pass arguments to the include file.
我试图使整个<head>
部分成为自己的包含文件。一个缺点是标题和描述和关键字将相同;我不知道如何将参数传递给包含文件。
So here is the code:
所以这里是代码:
index.php
索引.php
<?php include("header.php?header=aaaaaaaaaaaaaaaaaaaaa"); ?>
<body>
.....
..
.
header.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>
Obviously this doesn't work; how can I pass arguments to an included file?
显然这行不通;如何将参数传递给包含的文件?
回答by Rolf
Include has the scope of the line it's called from.
Include 具有调用它的行的范围。
If you don't want to create new global variables, you can wrap include()
with a function:
如果你不想创建新的全局变量,你可以include()
用一个函数包装:
function includeHeader($title) {
include("inc/header.php");
}
$title
will be defined in the included code whenever you call includeHeader
with a value, for example includeHeader('My Fancy Title')
.
$title
每当您includeHeader
使用值调用时,都会在包含的代码中定义,例如includeHeader('My Fancy Title')
.
If you want to pass more than one variable you can always pass an array instead of a string.
如果你想传递多个变量,你总是可以传递一个数组而不是一个字符串。
Let's create a generic function:
让我们创建一个通用函数:
function includeFile($file, $variables) {
include($file);
}
Voila!
瞧!
Using extractmakes it even neater:
使用提取物使它更整洁:
function includeFileWithVariables($fileName, $variables) {
extract($variables);
include($fileName);
}
Now you can do:
现在你可以这样做:
includeFileWithVariables("header.php", array(
'keywords'=> "Potato, Tomato, Toothpaste",
'title'=> "Hello World"
));
Knowing that it will cause variables $keywords
and $title
to be defined in the scope of the included code.
知道它会导致变量$keywords
并$title
在包含的代码范围内定义。
回答by Michal M
index.php:
索引.php:
<?php
$my_header = 'aaaaaaaaaaaaaaaaaaaa';
include 'header.php';
?>
and header.php
和 header.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>
It's not an ideal solution, but I understand it's your first steps in php.
这不是一个理想的解决方案,但我知道这是您在 php 中的第一步。
PS. Your Doctype doesn't match the code. I've adjusted your header html to be XHTML.
附注。您的 Doctype 与代码不匹配。我已将您的标题 html 调整为 XHTML。
回答by Michael Mrozek
You can't pass arguments to include
, but it has access to all variables you've already set. From the include
documentation:
您不能将参数传递给include
,但它可以访问您已经设置的所有变量。从include
文档:
When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward.
当一个文件被包含时,它包含的代码继承了包含发生所在行的变量范围。从那时起,调用文件中该行可用的任何变量都将在被调用文件中可用。
Thus:
因此:
index.php
索引.php
<?php
$header = 'aaaaaaaaaaaaaaaaaaaaa';
include("header.php");
?>
header.php
头文件
<title> <?php echo $header; ?> </title>
回答by Richard Key
Well marc, when you are using include, you can simply just set up a variable to use:
嗯,马克,当你使用 include 时,你可以简单地设置一个变量来使用:
<?php
$var = "Testing";
include("header.php");
?>
In your header file:
在你的头文件中:
<?php
echo $var;
?>
Allow your previously defined variables are usable in any include you have.
允许您之前定义的变量在您拥有的任何包含中可用。
回答by DampeS8N
you are over thinking it
你想多了
<?php
$header = "aaaaaaaaaaaaaaaaa";
include("header.php");
?>
::EDIT::
::编辑::
Decided I would add value
决定我会增加价值
The included file will gain the scope of where you included it. So if you include a file INSIDE a function:
包含的文件将获得包含它的范围。因此,如果您在函数中包含一个文件:
<?php
$get_me = "yes";
function haha()
{
include("file.php");
}
haha();
// And file.php looks like
echo $get_me; // notice + blank
?>
More over, you include the same file more than once to great effect.
更重要的是,您不止一次包含同一个文件,效果很好。
<?php
$output = "this";
include("cool_box.php");
$output = "will";
include("cool_box.php");
$output = "work";
include("cool_box.php");
?>
And even use this to load templates that become part of a method in a class. So you can do something like:
甚至使用它来加载成为类中方法一部分的模板。因此,您可以执行以下操作:
<?php
class template
{
private $name;
function __construct($name)
{
$this->name = preg_replace("/[^a-zA-Z0-9]/", "", $name);
}
function output(array $vars)
{
include($this->name.".php"); // Where $vars is an expected array of possible data
}
}
$head = new template("header");
$body = new template("body");
$head->output();
$head->output(array("content" => "this is a cool page"));
?>
回答by bcosca
defining a variable as a pseudo-argument/workaround before an include()
- as recommended by many - is a bad idea. it introduces a variable in the global scope. define a function in the included file instead to catch the arguments u want to pass.
将变量定义为伪参数/解决方法include()
- 正如许多人所推荐的 - 是一个坏主意。它在全局范围内引入了一个变量。在包含的文件中定义一个函数来捕获您想要传递的参数。
回答by Josef Sábl
This is good approach. I however would do it a bit inside out. Define a layout, a wrapper for your webpage and include your content file into it:
这是一个很好的方法。但是,我会从内到外做一点。定义一个布局,一个网页的包装器,并将您的内容文件包含在其中:
layout.phtml
<html>
<head>
... your headers go here
</head>
<body>
<? include $content ?>
</body>
</html>
Your content template file can look like this e.g.
您的内容模板文件可能如下所示,例如
content.phtml
<h1>hello world</h1>
<p>My name is <?= $name ?></p>
Then, you would have your main script (index) that will handle logic, connects to database etc.
然后,您将拥有将处理逻辑、连接到数据库等的主脚本(索引)。
index.php
$content = 'content.phtml';
$name = 'Marc'; //Can be pulled from database
include 'layout.phtml';
This way, you can nicely separate business logic and presentation. And it can help you cut repetitive code for parts of page like logo or navigation which are repeated on the whole site.
这样,您可以很好地分离业务逻辑和表示。它可以帮助您减少页面部分(如徽标或导航)在整个站点上重复的重复代码。
回答by DanielM
I noticed nobody suggested using a template engine. I came looking here because for the project I'm working with, a template engine isn't possible and that might be your situation too, however I thought it might be worth mentioning these: Twig(my preferred engine) and Smartyboth allow passing specific variables to includes.
我注意到没有人建议使用模板引擎。我来这里是因为对于我正在处理的项目,模板引擎是不可能的,这也可能是您的情况,但是我认为可能值得一提的是:Twig(我的首选引擎)和Smarty都允许通过要包含的特定变量。
I highlyrecommend the use of a template engine whenever possible, as it simplifies your front end code, adds a layer of abstraction between your front end and back end, and both Twig and Smarty automatically clean the variables you pass to them which helps mitigate XSS attacks.
我强烈建议尽可能使用模板引擎,因为它可以简化您的前端代码,在前端和后端之间添加一个抽象层,并且 Twig 和 Smarty 都会自动清理您传递给它们的变量,这有助于缓解 XSS攻击。
Twig Example
树枝示例
header.html
标题.html
<!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="{{ header }}" >
<meta name="Description" content="{{ header }}" >
<title> {{ 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>
index.html
索引.html
{% include 'header.html' with { 'header' : '<script>alert("this shouldnt work")</script>'} only %}
Body Text
{% include 'footer.html' %}
Smarty Example
聪明的例子
header.tpl
头文件
<!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="{$header}" >
<meta name="Description" content="{$header}" >
<title> {$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>
index.tpl
索引.tpl
{include 'header.tpl' header='<script>alert("this shouldnt work")</script>'}
Body Text
{include 'footer.tpl'}
回答by Aaron Hathaway
If you include a file it is just like inserting that code into the parent file. You could simply do this:
如果您包含一个文件,就像将该代码插入到父文件中一样。你可以简单地这样做:
<?php
$parameter = "Hello World";
include("header.php");
?>
and then in the header.php
然后在 header.php
<?php
$parameter = isset($parameter) ? $parameter : "Default Text";
// Use accordingly
?>
I used the isset()
method to verify that it has a value already and is instantiated.
我使用该isset()
方法来验证它是否已具有值并已实例化。