【问题标题】:How to pass arguments to an included file?如何将参数传递给包含的文件?
【发布时间】:2011-05-17 22:44:50
【问题描述】:

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

代码如下:

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>

显然这是行不通的;如何将参数传递给包含的文件?

【问题讨论】:

标签: php include


【解决方案1】:

Include 具有调用它的行的范围。

如果不想创建新的全局变量,可以用函数包裹include()

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

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

如果你想传递多个变量,你总是可以传递一个数组而不是一个字符串。

让我们创建一个通用函数:

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

瞧!

使用extract 使其更加整洁:

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

现在你可以这样做了:

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

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

【讨论】:

  • cmets 怎么了?这个答案是这个问题中最受好评的答案,并且它有一些 cmets(主要是赞美!),它们现在都消失了!
  • 一定是拥有足够权限的版主删除了这些内容。也许您可以在历史记录中查看。
  • 只是为了明确这一点:即使这些变量在子脚本中看起来是全局的(即在脚本的“全局”范围内没有声明的情况下可见),但它们不是。他们还将在子脚本中隐藏具有相同名称的全局变量,这是通常的 PHP 方式,即,在显式声明它们(如 global)或通过 $GLOBALS 之后,可以访问被屏蔽的全局变量.
  • 这个答案很棒
【解决方案2】:

我注意到没有人建议使用模板引擎。我来这里是因为对于我正在使用的项目,模板引擎是不可能的,这也可能是你的情况,但我认为可能值得一提:Twig(我的首选引擎)和@987654322 @两者都允许将特定变量传递给包含。

强烈建议尽可能使用模板引擎,因为它可以简化前端代码,在前端和后端之间添加抽象层,并且 Twig 和 Smarty 都会自动清理您传递给它们的变量有助于缓解 XSS 攻击。

树枝示例

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

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

聪明的例子

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

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

【讨论】:

    【解决方案3】:

    这是个好方法。然而,我会从里到外做一点。为您的网页定义一个布局、一个包装器并将您的内容文件包含在其中:

    layout.phtml
    
    <html>
        <head>
          ... your headers go here
        </head>
        <body>
          <? include $content ?>
        </body>
    </html>
    

    您的内容模板文件可能如下所示,例如

    content.phtml
    
    <h1>hello world</h1>
    
    <p>My name is <?= $name ?></p>
    

    然后,您将拥有处理逻辑、连接到数据库等的主脚本(索引)。

    index.php
    
    $content = 'content.phtml';
    $name = 'Marc'; //Can be pulled from database
    
    include 'layout.phtml';
    

    这样,您可以很好地分离业务逻辑和表示。它还可以帮助您减少在整个网站上重复的部分页面的重复代码,例如徽标或导航。

    【讨论】:

    • 该方法看起来不错,但暗示对我的代码进行了太多修改...将继续其他建议...
    • @marc:好的,但是下次你开始计划一个新项目时,请考虑一些人在这个线程中分享的建议,并更好地设计你的应用程序框架。
    【解决方案4】:

    include() 之前将变量定义为伪参数/解决方法 - 正如许多人所推荐的那样 - 是一个坏主意。它在全局范围内引入了一个变量。在包含的文件中定义一个函数来捕获你想要传递的参数。

    【讨论】:

    • 是的,但我认为你现在对他来说太领先了。我认为在发现如何将网页组合在一起的更合适方法之前,他的方法值得进行一些探索。
    • 呃等等,你是怎么做到的?
    【解决方案5】:

    你想多了

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

    ::编辑::

    决定我会增加价值

    包含的文件将获得您包含它的范围。因此,如果您在函数中包含文件:

    <?php
    $get_me = "yes";
    function haha()
    {
    include("file.php");
    }
    haha();
    
    // And file.php looks like
    
    echo $get_me; // notice + blank
    
    ?>
    

    此外,您不止一次地包含同一个文件,效果非常好。

    <?php
    
    $output = "this";
    include("cool_box.php");
    
    $output = "will";
    include("cool_box.php");
    
    $output = "work";
    include("cool_box.php");
    
    ?>
    

    甚至可以使用它来加载成为类中方法的一部分的模板。所以你可以这样做:

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

    【讨论】:

    • 再做一步,输出缓冲包含的文件,然后返回字符串,就可以构建完整的模板引擎了。再迈出这一步,你就拥有了 90% 的框架。
    • 我看起来会变得更好,而且那个方法看起来真的很好......至少当功能完成时,代码就是诗!
    • PHP 非常适合编写富有诗意的代码。它也非常适合写别人无法理解的诗歌。双刃剑。
    • @DampeS8N - 回复:double-edged sword - 这就是内联文档的用途。 ;-D.
    【解决方案6】:

    index.php:

    <?php
    $my_header = 'aaaaaaaaaaaaaaaaaaaa';
    include '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>
    

    这不是一个理想的解决方案,但我知道这是您在 php 中的第一步。

    PS。您的 Doctype 与代码不匹配。我已将您的标头 html 调整为 XHTML。

    【讨论】:

    • 这解释了您的基本问题。但是你应该继续寻找更好的方法来把 html 和 php 放在一起。
    • @JosefSábl 例如?
    • MVC 框架。上面例子的问题是包含的文件不知道变量 $my_header 来自哪里,这让人很头疼。拥有一个这样的变量或非常简单的网页是可以的,但是依赖这些技术的全规模应用程序的维护将很快成为噩梦。相信我,我必须保持一个:-)
    【解决方案7】:

    如果您包含一个文件,就像将该代码插入到父文件中一样。你可以这样做:

    <?php
    $parameter = "Hello World";
    include("header.php");
    ?>
    

    然后在header.php

    <?php
    $parameter = isset($parameter) ? $parameter : "Default Text";
    // Use accordingly
    ?>
    

    我使用isset() 方法来验证它是否已经有一个值并被实例化。

    【讨论】:

      【解决方案8】:

      您不能将参数传递给include,但它可以访问您已经设置的所有变量。来自include documentation

      当一个文件被包含时,它包含的代码继承了包含发生的行的变量范围。从那时起,调用文件中该行的任何可用变量都将在被调用文件中可用。

      因此:

      index.php

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

      header.php

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

      【讨论】:

        【解决方案9】:

        马克,当你使用包含时,你可以简单地设置一个变量来使用:

        <?php
          $var = "Testing";
          include("header.php");
        ?>
        

        在你的头文件中:

        <?php
          echo $var;
        ?>
        

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

        【讨论】:

          猜你喜欢
          • 2021-10-16
          • 2012-09-23
          • 1970-01-01
          • 2015-12-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多