PHP 自动加载命名空间


PHP autoload namespace

我想自动加载我的类,只放置命名空间+文件名。

例:

目录骨架:

'var'www
  |_ foo
  |  |_ A.php
  |  |_ B.php
  |  
  |_ index.php

答.php:

<?php
namespace foo'A;
class A {
   private $a;
   public function __construct($a) {
       $this->a = $a;
   }
}

乙.php:

<?php
namespace foo'B;
use foo'A;
class B extends A {
    private $b;
    public function __construct($a, $b) {
        parent::__construct($a);
        $this->b = $b;
    }   
}

索引.php:

<?php
use foo'B;
define('ROOT', __DIR__ . DIRECTORY_SEPARATOR);
$b = new B('s', 2);
function __autoload($classname) {
    $namespace = substr($classname, 0, strrpos($classname, ''''));
    $namespace = str_replace('''', DIRECTORY_SEPARATOR, $classname);
    $classPath = ROOT . str_replace('''', '/', $namespace) . '.php';
    if(is_readable($classPath)) {
        require_once $classPath;
    }
}

问题是在类 A 和 B 中,我用类名声明命名空间,当我使用它时,我打印了__autoload的变量并且是正确的,调用构造函数时 bur,找不到类。

错误:

Fatal error: Class 'foo'A' not found in /var/www/foo/B.php on line 7

如果我只实例化 A,而不使用 B,问题是一样的。

我需要这样做,因为我希望在 B 类中,如果你不放 use 语句,你就不能使用 A,让它做得更严格。

如果你理解我的问题,我现在不知道我的解释,但无论如何感谢任何建议!!

PD:对不起我的英语水平。

你的代码应该是类中的代码:

答.php

<?php
namespace foo;
class A {
   private $a;
   public function __construct($a) {
       $this->a = $a;
   }
}

B.php

<?php
namespace foo;
class B extends A {
    private $b;
    public function __construct($a, $b) {
        parent::__construct($a);
        $this->b = $b;
    }   
}