php - 从 php.ini 包含的路径自动加载命名空间类

标签 php namespaces autoload spl-autoload-register spl-autoloader

我有一个在项目外的目录中命名的类。该目录包含在 include_path 中指示。我想使用 spl_autoload class 自动加载类。但是,我只收到错误。它似乎只是试图从项目目录加载文件。

这是一台 Windows 机器,但我希望它可以在 Windows 或 Linux 机器上运行

##incude_path directive##
include_path = ".;C:\xampp\php\PEAR;C:\Users\Joey\Dropbox\web\global_includes;C:\Users\Joey\Dropbox\web\global_includes\utility;C:\Users\Joey\Dropbox\web\global_includes\utility\arrayTools"

    //index.php
    require 'bootstrap.php';

    $array = array('Hello','world');
    $array[] = array('Hello','world','2');
    $array[2][1] = array('Hello','world',3);

    echo '<p>The number of dimesions: '.utility\arrayTools\arrayTools::numberOfDimensions($array).'</p>';

    //bootstrap.php
    spl_autoload_register('autoLoader::autoLoad');


    class autoLoader
    {
      public static function autoLoad($file)
      {
          if(is_string($file)){
              if(file_exists("$file.php")){
                  try{
                     include "$file.php";
                  }catch(Exception $exc){
                      echo '<pre><p>'.$exc->getMessage().'</p>'.$exc->getTraceAsString().'</pre>';
                  }
              }
          }
      }
    }

最佳答案

我找到了解决方法,但必须有更好的方法

<?php
//bootstrap.php
spl_autoload_register('autoLoader::autoLoad');

class autoLoader
{
    public static function autoLoad($file)
    {
        if(is_string($file)){
            $path_and_file = self::fileExists($file);
            if($path_and_file !== FALSE){
                include $path_and_file;
            }else{
                //This is for debugging purposes on dev only
                throw new Exception("$file Does Not exsist");
            }
        }else{
            throw new Exception('Classes must be a string');
        }
    }

    protected static function fileExists($file)
    {
        $include_paths = explode(';',get_include_path());
        foreach($include_paths as $path){
            if(file_exists("$path\\$file.php")){
                return "$path\\$file.php";
            }elseif(file_exists(str_replace('\\','/',"$path\\$file.php"))){
                return str_replace('\\','/',"$path\\$file.php");
            }
        }

        return FALSE;
    }

}

关于php - 从 php.ini 包含的路径自动加载命名空间类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13237883/

相关文章:

javascript - var myObj = myObj || 有什么好处{ } 当 myObj 已经存在时?

symfony - 未找到类 'Symfony\Component\Yaml\Yaml'

php - $facebook->api ('/me' ) 返回 NULL

javascript - 拉维尔 : Data-table search option not working using relationship table field

php - Android数组转mysql数据库?

namespaces - 如何使 JAXB 解码器忽略前缀?

php - 谷歌地图 - 商店定位器 - 多个过滤器 - 数据库与客户端

c++ - 什么时候初始化匿名命名空间数据?

ruby-on-rails - 递归包括所有模型子目录

overriding - 如何重写(装饰)内置的 Fish 函数