【问题标题】:do included files in php use information from the files that included them?php 中包含的文件是否使用包含它们的文件中的信息?
【发布时间】:2012-01-16 19:15:44
【问题描述】:

假设我有以下文件

示例 1

functions.php

<?php
     session_start();
     function getSessionData(){
         ...
         // returns array
     }
?>

index.php

<?php
    session_start();
    include("functions.php");
    $sessionData = getSessionData();
?>
<html>
    <head>
        <title>test</title>
    </head>
    <body>
        <?php print_r($sessionData); ?>
    </body>
</html>

现在index.php 包含functions.php。因为我在index.php中有session_start(),这是否意味着它会自动添加到functions.php中(看到函数包含在索引中?)

我不确定我是否说清楚了。

示例 2

config.php

<?php
    $url = "www.example.com";
?>

functions.php

<?php
     include("config.php");
     function getSomething(){
         ...
         return $url
     }
?>

index.php

<?php
    include("config.php");
    include("functions.php");
    $some_var = getSomething();
?>
<html>
    <head>
        <title>test</title>
    </head>
    <body>
        <?=$some_var;?>
    </body>
</html>

现在 functions.php 和 index.php 都包含 config.php...

但是因为 config 已经包含在 index.php...

这是否意味着它必须包含在函数中?

我想我只是把自己弄糊涂了:)

【问题讨论】:

  • 您可以根据需要多次包含一个文件,只要它不定义任何函数/对象。如果您双重包含函数定义文件,您将收到“无法重新声明任何()”致命错误。简单的变量、输出块等等……都可以。

标签: php include


【解决方案1】:

是的。您可以将包含视为简单地将代码粘贴到包含语句所在的文件中。

在示例 2 中,您不需要在索引中再次包含 config,因为它已经包含在函数中(反之亦然) - 您实际上在执行的操作是在 config.php 中运行代码两次(例如,可以通过使用include_once 来防止)。

示例 1 中的 session_start() 也是如此。加载索引时会发生以下情况:

  1. session_start
  2. 包括functions.php
    1. session_start(现在不需要)
    2. function getSessionData() {..}
  3. (返回索引)- 致电getSessionData()

此外,在您的第二个示例中,您将无法在该函数中访问 $url,除非在它之前调用 global $url(在函数内部)。

【讨论】:

  • 所以在第一个例子中。我不需要再次调用 session_start() 因为它已经在索引中调用了?
猜你喜欢
  • 1970-01-01
  • 2014-12-01
  • 1970-01-01
  • 2011-08-02
  • 1970-01-01
  • 2012-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多