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

时间:2021-12-12 04:19:06

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.

我正在尝试使整个节自己的include文件。一个缺点是标题和描述和关键字是一样的;我不知道如何将参数传递给include文件。

So here is the code:

这里是代码:

index.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?

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

9 个解决方案

#1


42  

index.php:

index . 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。

#2


83  

Since nobody seems to have mentioned it... Include has the scope of the line it's called from. So if you don't want to create new global variables, you can call include from within a function. Example:

因为似乎没有人提到它……Include具有调用它的行范围。如果不想创建新的全局变量,可以在函数中调用include。例子:

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

$title will be defined in the included file. If you want more then one variable to be visible from the included file, you can pass an array... let's create a generic function

$title将在包含的文件中定义。如果您想要从包含的文件中看到更多的变量,您可以传递一个数组……让我们创建一个泛型函数

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

Voila!

瞧!

If you want the included code to be able to change the values of the passed variables, you can pass by reference (using "&"):

如果您希望所包含的代码能够更改所传递变量的值,您可以通过引用传递(使用“&”):

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

Now if you change the value of $title in the included file, it's value will also change in the "main file", the calling code. Applying this to arrays, you might have to do this:

现在,如果您在包含的文件中更改$title的值,它的值也将在“主文件”(调用代码)中更改。将这个应用到数组中,您可能需要这样做:

$variables['title'] = &$title;
$variable['someOtherVar'] = &$blah;

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

But I'm getting carried away, and I'm not even sure that works anymore. I think it should but I have a bad experience using passing by reference inside arrays in PHP and I think it's better to avoid it.

但我已经有点忘乎所以了,我甚至不确定这种方法是否有效。我认为应该这样,但是我有一个不好的经验,在PHP中使用数组内部传递引用,我认为最好避免它。

PS: How about that (using extract):

PS:怎么样(用extract):

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

Now all you have to do is:

现在你要做的就是:

includeFileWithVariables("header.php",array('header'=>'aaaaa'));

Here we just passed one variable in the array, but there could be more.

这里我们只是在数组中传递了一个变量,但是可能还有更多。

#3


11  

You can't pass arguments to include, but it has access to all variables you've already set. From the include documentation:

您不能传递参数来包含,但是它可以访问您已经设置的所有变量。

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
$header = 'aaaaaaaaaaaaaaaaaaaaa';
include("header.php");
?>

header.php

<title> <?php echo $header; ?> </title>

#4


2  

Well marc, when you are using include, you can simply just set up a variable to use:

marc,当你使用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.

允许您以前定义的变量在任何包含中都可用。

#5


2  

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"));

?>

#6


2  

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()之前,将变量定义为伪参数/解决方案是一个坏主意。它在全局范围内引入了一个变量。在包含的文件中定义一个函数,以捕获您想要传递的参数。

#7


1  

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.

通过这种方式,您可以很好地分离业务逻辑和表示。它可以帮助你减少重复代码的部分页面,如标志或导航,在整个网站重复。

#8


0  

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()方法来验证它是否已经有一个值,并已实例化。

#9


0  

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 Smarty both allow passing specific variables to includes.

我注意到没有人建议使用模板引擎。我来这里查看是因为我正在处理的项目,一个模板引擎是不可能的,这可能也是您的情况,但是我想可能值得一提的是:Twig(我的首选引擎)和Smarty都允许传递特定的变量。

I highly recommend 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

header.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

index . html

{% include 'header.html' with { 'header' : '<script>alert("this shouldnt work")</script>'} only %}
Body Text
{% include 'footer.html' %}

Smarty Example

Smarty的例子

header.tpl

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

index.tpl

{include 'header.tpl' header='<script>alert("this shouldnt work")</script>'}
Body Text
{include 'footer.tpl'}

#1


42  

index.php:

index . 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。

#2


83  

Since nobody seems to have mentioned it... Include has the scope of the line it's called from. So if you don't want to create new global variables, you can call include from within a function. Example:

因为似乎没有人提到它……Include具有调用它的行范围。如果不想创建新的全局变量,可以在函数中调用include。例子:

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

$title will be defined in the included file. If you want more then one variable to be visible from the included file, you can pass an array... let's create a generic function

$title将在包含的文件中定义。如果您想要从包含的文件中看到更多的变量,您可以传递一个数组……让我们创建一个泛型函数

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

Voila!

瞧!

If you want the included code to be able to change the values of the passed variables, you can pass by reference (using "&"):

如果您希望所包含的代码能够更改所传递变量的值,您可以通过引用传递(使用“&”):

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

Now if you change the value of $title in the included file, it's value will also change in the "main file", the calling code. Applying this to arrays, you might have to do this:

现在,如果您在包含的文件中更改$title的值,它的值也将在“主文件”(调用代码)中更改。将这个应用到数组中,您可能需要这样做:

$variables['title'] = &$title;
$variable['someOtherVar'] = &$blah;

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

But I'm getting carried away, and I'm not even sure that works anymore. I think it should but I have a bad experience using passing by reference inside arrays in PHP and I think it's better to avoid it.

但我已经有点忘乎所以了,我甚至不确定这种方法是否有效。我认为应该这样,但是我有一个不好的经验,在PHP中使用数组内部传递引用,我认为最好避免它。

PS: How about that (using extract):

PS:怎么样(用extract):

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

Now all you have to do is:

现在你要做的就是:

includeFileWithVariables("header.php",array('header'=>'aaaaa'));

Here we just passed one variable in the array, but there could be more.

这里我们只是在数组中传递了一个变量,但是可能还有更多。

#3


11  

You can't pass arguments to include, but it has access to all variables you've already set. From the include documentation:

您不能传递参数来包含,但是它可以访问您已经设置的所有变量。

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
$header = 'aaaaaaaaaaaaaaaaaaaaa';
include("header.php");
?>

header.php

<title> <?php echo $header; ?> </title>

#4


2  

Well marc, when you are using include, you can simply just set up a variable to use:

marc,当你使用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.

允许您以前定义的变量在任何包含中都可用。

#5


2  

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"));

?>

#6


2  

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()之前,将变量定义为伪参数/解决方案是一个坏主意。它在全局范围内引入了一个变量。在包含的文件中定义一个函数,以捕获您想要传递的参数。

#7


1  

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.

通过这种方式,您可以很好地分离业务逻辑和表示。它可以帮助你减少重复代码的部分页面,如标志或导航,在整个网站重复。

#8


0  

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()方法来验证它是否已经有一个值,并已实例化。

#9


0  

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 Smarty both allow passing specific variables to includes.

我注意到没有人建议使用模板引擎。我来这里查看是因为我正在处理的项目,一个模板引擎是不可能的,这可能也是您的情况,但是我想可能值得一提的是:Twig(我的首选引擎)和Smarty都允许传递特定的变量。

I highly recommend 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

header.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

index . html

{% include 'header.html' with { 'header' : '<script>alert("this shouldnt work")</script>'} only %}
Body Text
{% include 'footer.html' %}

Smarty Example

Smarty的例子

header.tpl

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

index.tpl

{include 'header.tpl' header='<script>alert("this shouldnt work")</script>'}
Body Text
{include 'footer.tpl'}