Php定义的函数不与include一起传输

时间:2016-02-16 22:54:32

标签: php php-include

所以,我有一个名为init.php的文件应该放在我网站上的每个页面之上。在这种情况下,它在我的index.php中。在init.php里面是一段代码,其中包含名为include的文件夹中的所有文件。当我尝试调用在应该包含的文件中定义的index.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

3 个答案:

答案 0 :(得分:1)

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

作为一个解决方案,尝试用双反斜杠\\替换你的反斜杠,它会逃避反斜杠本身并将其解释为普通字符,或者只使用斜杠/而不是反斜杠。

答案 1 :(得分:1)

您所要做的就是将目录分隔符从正斜杠/更改为反斜杠\。我已经在我的机器上进行了测试,但它已经有效了。

答案 2 :(得分:0)

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

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