【问题标题】:Simple Autoload class and include example简单的自动加载类并包含示例
【发布时间】:2014-03-08 23:54:03
【问题描述】:

好的,我试图了解自动加载,我有点困惑,我读了一堆帖子,现在我觉得我更困惑了,如果我有一个简单的例子,我想我可以理解它。

假设我有一个简单的项目:

var/www/myproject/index.php

然后我有 var/www/myproject/classes/database.php 这个:

class Database {
    function __construct() {
        echo 'This is my Database Class <br />';
    }
}

还有 var/www/myproject/classes/functions.php 这个:

class Functions {
      function __construct() {
          echo 'This is my functions class <br />';
      } 
}

还有 var/www/myproject/classes/users.php 这个:

class Users {
      function __construct() {
          echo 'This is my user class <br />';
      } 
}

然后假设我在这里有 2 个包含:

var/www/myproject/includes/header.php

var/www/myproject/includes/footer.php

那么我将如何自动加载所有这些文件和类。我在想这样的事情,但我遇到的示例似乎非常特定于他们的设置,或者只适用于一个文件夹,或者包含我没有掌握的命名空间。

我在想我的索引可能看起来像这样:

function __autoload($class_name) {
    require_once 'classes/'.$class_name . '.php';
}

但这不适用于包含页眉和页脚,所以也许这样的东西更合适

$path = array('classes/','includes/');
foreach ($path as $directory) {
    if (file_exists($directory . ? . '.php')) {
        require_once ($directory . ? . '.php');
    }

这个想法是它会包含它找到的目录中的所有内容,但我不知道该怎么做,?应该代表通配符,我知道这行不通,我试图举例说明我正在尝试做什么。

这一定是人们经常遇到的事情,我确定有一个很好的解决方案,只是找不到一篇解释得足够好让我理解的文章

【问题讨论】:

  • 页眉页脚的内容是什么?自动加载适用于类,但并非真正适用于 HTML 标记,包括通常的页眉和页脚。此外,自动加载用于定位要包含的类文件一次,而在脚本执行期间可能会多次包含页眉或页脚。对于那些,请考虑只定义一个知道如何查找myproject/includes/{$name}.php 的函数。这确实是与类自动加载不同的概念。
  • 好的,这很有帮助,可能解释了为什么我没有找到合适的答案,因为我基本上是在寻找 2 个不同问题的 1 个解决方案。

标签: php include autoload


【解决方案1】:

如果您在项目命名空间中使用,我建议使用简单代码:

 class ClassLoader {

      public  function handle($class) {
         $file = str_replace('\\', '/', $class.'.php');
         if(!file_exists($file)){
             throw new \Exception('class '.$class.' file not exists');
         }
         include_once $file;
     }

 }

 $autloader = new Classes\ClassLoader;
 spl_autoload_register(array($autloader, 'handle'));

// 从现在开始,您可以从类的命名空间中指定的目录中加载所有类,例如

 /////////////////////////////////////////////
 // directory => framework/classes/User.php //
 /////////////////////////////////////////////

 namespace framework\classes;
 class User {
     public function helloWorld(){
             echo 'hello World';
     }
 }

 //////////////////////// 
 // and here index.php //
 ////////////////////////

 $autloader = new Classes\ClassLoader;
 spl_autoload_register(array($autloader, 'handle'));
 $user = new \framework\classes\User();
 $user->helloWorld();

【讨论】:

    猜你喜欢
    • 2010-12-12
    • 2011-12-04
    • 1970-01-01
    • 2014-01-05
    • 1970-01-01
    • 1970-01-01
    • 2012-08-15
    • 2012-06-17
    • 1970-01-01
    相关资源
    最近更新 更多