【问题标题】:Php autoload projectphp自动加载项目
【发布时间】:2012-12-06 02:51:44
【问题描述】:

我有一个这样的项目:

现在我想自动加载文件夹类和子文件夹中的所有 php 文件。

我可以这样做:

$dirs = array(
   CMS_ROOT.'/classes',
   CMS_ROOT.'/classes/layout',
   CMS_ROOT.'/classes/layout/pages'
);
foreach( $array as $dir) {
  foreach ( glob( $dir."/*.php" ) as $filename ) {
    require_once $filename;
  }
}

但我不喜欢这个。例如。

“layout/pages/a.php”扩展了“layout/pages/b.php”

现在我收到一个错误,因为首先加载了 a.php。你们是如何加载项目文件的?上课?

已解决:)

这是我现在的代码:

spl_autoload_register('autoloader');
function autoloader($className) {
    $className = str_replace('cms_', '', $className);
    $className = str_replace('_', '/', $className);

    $file = CLASSES.'/'.$className.'.php';
    if( file_exists( $file ) ) {
    require_once $file;
    }
}

【问题讨论】:

标签: php include project require autoload


【解决方案1】:

你应该试试这个

<?php

spl_autoload_register('your_autoloader');

function your_autoloader($classname) {
    static $dirs = array(
      CMS_ROOT.'/classes',
      CMS_ROOT.'/classes/layout',
      CMS_ROOT.'/classes/layout/pages'
   );
   foreach ($dirs as $dir) {
      if (file_exists($dir . '/'. $classname. '.php')) {
          include_once $dir . '/' . $classname . '.php';
      }
   }
}

your_autoloader 注册到spl_autoload_register() 后,每次访问以下类时,php 解释器都会调用它:

  • 尚未加载require_once()include_once()

  • 不是 PHP 内部的一部分

【讨论】:

  • 谢谢!那是我提出的一个愚蠢的问题。我可以自己弄清楚,但没有时间。非常感谢 hek2mgl! :)
猜你喜欢
  • 1970-01-01
  • 2022-11-15
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 1970-01-01
  • 2014-11-02
  • 2014-11-18
  • 2012-09-22
相关资源
最近更新 更多