【问题标题】:Php defined functions don't transfer with includePHP 定义的函数不与 include 一起传输
【发布时间】:2016-02-16 22:54:32
【问题描述】:

所以,我有一个名为 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

【问题讨论】:

  • 使用/作为目录分隔符
  • 也试过了,但什么也没做。
  • glob 会返回您期望的结果吗?
  • 试试require看看有没有错误
  • 仍然给出相同的Call to undefined function errors_return()

标签: php php-include


【解决方案1】:

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

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

【讨论】:

  • 它仍然给我一个未定义函数错误的调用,但仅在 index.php 页面上。如果我通过浏览器访问 init.php 并让它调用一个函数,那出于某种原因。但是当它包含在另一个页面中时,应该定义的功能将不起作用。
  • 您是否尝试将 init.php 中的 include 也替换为 require ?我认为那里的循环可能有路径问题。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-02
      相关资源
      最近更新 更多