dongqiaochi2711 2014-11-04 20:53
浏览 34
已采纳

自动加载命名空间类

I have searched high and low for an answer and tried every example, but this still fails to find my classes. Why do I keep getting Fatal error: Class 'ProjectMorpheus\model\Database' not found in C:\Portables\xampp\htdocs\ProjectMorpheus\config\config.php on line 23

/ProjectMorpheus
  /model
    Database.class.php
  /config
    config.php

So my Database class has a namespace like this:

namespace ProjectMorpheus\model;
class Database { ... }

Finally, my config.php has a function autoloader function (Note: __SITE_PATH = 'C:\Portables\xampp\htdocs\ProjectMorpheus\'):

/*** auto load model classes ***/
function __autoload($class){
  $parts = explode('\\', $class);
  include __SITE_PATH . 'model/' . end($parts) . '.class.php';
}

$dbh = \ProjectMorpheus\model\Database::getInstance($dsn, $username, $password);

Using spl_autoloader appears to work, but why? My only guess is that $class is not the same in both instances. My spl_function looks like:

spl_autoload_register(function($class){
   $parts = explode('\\', $class);
   include __SITE_PATH . 'model/' . end($parts) . '.class.php';
});
  • 写回答

1条回答 默认 最新

  • douzhiling3166 2014-11-04 21:22
    关注

    Why don't you use PSR-0 or PSR-4 autoloader standards?

    They even have ready-to-use autoloader class on GitHub As long as you will follow the rules, you won't have any issues and your code will be PSR.

    Although I wouldn't recommend but if you would like to insist using the code above for autoloading classes (only in models folder) then try to dump what is the value of __SITE_PATH . 'model/' . end($parts) . '.class.php'; and check if you can access it. You can even try to copy and paste the path to your file explorer to see if the location is reachable and file exists in that directory.

    P.S. I tried to add this as a comment but I couldn't due to low rep. points (being new around here and all).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型