名前空間とファイル名だけを入れてクラスを自動ロードしたい。
例:
ディレクトリのスケルトン:
\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;
}
}
index.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: 私の英語力で申し訳ありません。