【问题标题】:How to include files inside a function and still grant the functions of included file global scope in php如何在函数中包含文件并仍然在php中授予包含文件全局范围的功能
【发布时间】:2012-01-17 13:51:54
【问题描述】:

我被一些 ABSTRACTION & ORGANIZATION 错误所困扰,我决定使用一个名为 Loader 的类在我的 php 应用程序中包含文件,看起来像这样

class Loader
{
    public $loadedFiles=array();

    public function isLoaded($fileName)
    {
        if(in_array($fileName,$this->loadedFiles))
        return true;
        else 
        return false;
    }

    public function load()
    {
        $fileList=func_get_args();
        foreach ($fileList as $file)
        {
            if(!$this->isLoaded($file))
            {
                $flag=include(ROOT_DIR_PATH.'includes'.DS.$file);
                if($flag)
                {
                    $this->loadedFiles[]=$file;

                }
                else
                return false;
            }
        }
    }
}

现在我可以使用类似的方法在我的应用中包含文件

$loader=new Loader();
$loader->load('db.class.php','utility.php','objects.php');

但问题是现在上述方法包含的文件的所有功能都被授予上述方法load的范围。现在我不能使用包含文件的任何功能。每当我使用上述包含文件的任何功能时,我都会收到一条警告说undefined function。有什么方法可以将全局范围授予包含文件的功能。

【问题讨论】:

  • 是路径 $flag=include(ROOT_DIR_PATH.'includes'.DS.$file);对吗?

标签: php include scope


【解决方案1】:

看起来问题出在其他地方。我试图模拟你试图做的事情,它对我有用。
include1.php

 <?php
 function tester()
     echo "This is tester\n";
 }

include2.php

<?php

class Loader {
    public function load() {
        $var = include('include1.php');
    }
}

$loader = new Loader();
$loader->load();
tester();

结果是这样的:这是测试员

不存在任何范围界定问题。正如@JackTurky 提到的,检查路径。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-05
    • 2012-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多