Php 简单的自动加载类和include示例

Php 简单的自动加载类和include示例,php,include,autoload,Php,Include,Autoload,好吧,我试着让我的头围绕自动加载,我有点困惑,我读了一堆帖子,现在我觉得我更困惑,如果我有一个简单的例子,我想我可以让我的头围绕它 假设我有一个简单的项目: 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/index.php

然后我有var/www/myproject/classes/database.php,其中包含:

class Database {
    function __construct() {
        echo 'This is my Database Class <br />';
    }
}
class Functions {
      function __construct() {
          echo 'This is my functions class <br />';
      } 
}
class Users {
      function __construct() {
          echo 'This is my user class <br />';
      } 
}
但这样做对页眉和页脚的包含不起作用,所以这样做可能更合适

$path = array('classes/','includes/');
foreach ($path as $directory) {
    if (file_exists($directory . ? . '.php')) {
        require_once ($directory . ? . '.php');
    }
这个想法是,它将包括它找到的目录中的所有内容,但我不知道如何做到这一点?应该表示一个通配符,我理解这是行不通的,我试图给出一个我想做的例子


这一定是人们经常遇到的问题,我相信有一个很好的解决方案,只是找不到一篇文章来解释它,让我能够理解

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

 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();

页眉和页脚的内容是什么?自动加载适用于类,但实际上不适用于HTML标记,例如页眉和页脚。此外,自动加载用于定位要包含的类文件一次,而在脚本执行过程中可能会多次包含页眉或页脚。对于那些,只需定义一个函数,它知道如何查找<代码> MyStudio/Is/{$Nord}。PHP<代码>它确实是一个不同于类AutoLooDeP的概念。OK是有帮助的,可能解释了为什么我找不到合适的答案,因为我基本上在寻找1个解决2个不同问题的方法。
 /////////////////////////////////////////////
 // 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();