2

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

例子:

目录骨架:

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

A.php:

<?php

namespace foo\A;

class A {

   private $a;

   public function __construct($a) {
       $this->a = $a;
   }

}

B.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和BI中用类名声明了命名空间,当我使用它时,我打印了__autoload的变量并且是正确的,在调用构造函数时,没有找到类。

错误:

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

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

我需要这样做,因为我希望在 B 类中,如果不放置 use 语句,则不能使用 A,以使其更严格。

如果您理解我的解释问题,我现在不明白,但无论如何感谢您的任何建议!

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

4

1 回答 1

4

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

一个.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;
    }   

}
于 2013-11-12T23:59:59.957 回答