duanji1056
2014-07-13 08:09
浏览 63
已采纳

当命名空间使用时,PHP spl_autoload_register无法加载具有require范围的类

Ok!!! Now, i feel like clue less why spl_autoload_register() can't able to load the class.

My folder structure is like this..

  • application

    • controller
      • welcome.php
  • system

    • core
      • BaseController.php
      • Load.php
  • index.php

My BaseController.php code

<?php
namespace system\core;

class BaseController {
    public function __construct() {
        spl_autoload_register(array($this, 'loader'));
    }

    private function loader($className) {              
        $className = ltrim($className, '\\');
        $fileName  = '';
        $namespace = '';
        if ($lastNsPos = strrpos($className, '\\')) {
            $namespace = substr($className, 0, $lastNsPos);
            $className = substr($className, $lastNsPos + 1);
            $fileName  = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
        }
        $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';

        require $fileName;
    }
}

My Load.php code

<?php
namespace system\core;

class Load  {
    public function view()
    {
        echo "Method for loading view";
    }
}

My welcome.php code

<?php
class Welcome extends system\core\BaseController {
    public function index()
    {
        $obj_load = new Load();
        $obj_load->view();
    }
}

My index.php code

<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');

require_once "system/core/BaseController.php";
require_once "application/controller/welcome.php";
$welcome = new welcome();
echo $welcome->index();

When i'm executing this code(index.php) I'm getting following error...

Fatal error: Class 'Load' not found in /var/www/nut/test/application/controller/welcome.php on line 5

But, If i remove the namespace from Load.php i'm not getting any error. I can't able to understand why that namespace(used in Load.php) is creating error.

Any thought...

Regards

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题