【问题标题】:autoloading namespaced classes from a php.ini included path从 php.ini 包含的路径自动加载命名空间类
【发布时间】:2012-10-25 15:06:51
【问题描述】:

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

这是一台 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>';
                  }
              }
          }
      }
    }

【问题讨论】:

  • Yaiks,静态 .. 不支持命名空间 .. 不支持路径 .. pffff ..
  • 但是如果我将文件夹的副本移动到项目目录中,它就可以正常工作。所以由于某种原因,它只检查项目目录而不是所有的包含路径目录
  • 所以我拿出了静态方法,同样的问题。就像它只在项目文件夹中查找一样。没有来自包含路径的路径

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


【解决方案1】:

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

<?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;
    }

}

【讨论】:

    猜你喜欢
    • 2012-03-09
    • 1970-01-01
    • 2015-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-10
    • 2011-11-19
    • 2013-11-25
    相关资源
    最近更新 更多