PHP 定义的函数不与包含一起传输


Php defined functions don't transfer with include

所以,我有一个名为init的文件.php它应该放在我网站的每个页面的顶部。在这种情况下,它在我的索引中.php。在该 init 中.php是一段代码,其中包含名为 include 的文件夹中的所有文件。当我尝试调用索引中的函数时.php应该包含在应该包含的文件中定义的文件,我只是收到一个错误,说Call to undefined function errors_return().知道这里出了什么问题吗?

//index.php
<?php
include "php'init.php";
//errors_return(); is a defined function in functions.php
?>
//init.php
<?php
//error_reporting(0);
foreach (glob("include'*.php") as $filename) {
     include $filename;
}
$GLOBALS["errors_log"] = array();
session_start();
?>
//sample of functions.php
<?php
function error($msg = "default error"){
    array_push($GLOBALS["errors_log"],$msg);
}
function errors_return(){
    if(!empty($GLOBALS["errors_log"])){
        foreach($GLOBALS["errors_log"] as $e){
            echo '<p style="position:relative;">'.$e.'</p>';
        }
    }
    else {
        return null;
    }
}
?>
folder structure
root (folder)
   index.php
   php (folder)
      init.php
      include (folder)
          functions.php

您在代码中使用了反斜杠'双引号。PHP 中的反斜杠告诉解释器转义序列开始,反斜杠后面的字符将被尝试解释为这样的转义序列。

作为解决方案,请尝试将反斜杠替换为双反斜杠''这将转义反斜杠本身并将其解释为普通字符,或者仅使用斜杠/而不是反斜杠。

您所

要做的就是将目录分隔符从正斜杠/更改为反斜杠'。我已经在我的机器上对此进行了测试,它已经工作了。

所以我发现了这里的问题所在。似乎当包含发生在foreach循环中时,它不在文件本身中包含的正确范围内。我不知道如何解决这个问题。

foreach (glob("include'*.php") as $filename) {
     include $filename; //not included with the file
}
include "sample/dir/sample.php"; //included the with file