[英]PHP autoload namespace
I want to autoload my classes putting only the namespace + the filename. 我想自动加载类,只放置名称空间+文件名。
Example: 例:
directories skeleton: 目录框架:
\var\www
|_ foo
| |_ A.php
| |_ B.php
|
|_ index.php
A.php: a.php只会:
<?php
namespace foo\A;
class A {
private $a;
public function __construct($a) {
$this->a = $a;
}
}
B.php: 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: 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;
}
}
The problem is that in the class A and BI declare the namespace with the classname, and when I use it I print the variables of the __autoload and are correct, bur when call the constructor, don't find the class. 问题在于,在类A和BI中用类名声明了名称空间,当我使用它时,我将打印__autoload的变量,并且是正确的,调用构造函数时bur找不到类。
error: 错误:
Fatal error: Class 'foo\A' not found in /var/www/foo/B.php on line 7
If I only instantiate A, and I don't use B, the problem is the same. 如果我仅实例化A,而我不使用B,则问题是相同的。
I need to do it like this, because I want that in class B, you can't use A if you don't put the use statement, to do it more strict. 我需要这样做,因为我希望在B类中,如果不放置use语句,则不能使用A,以使其更加严格。
I don't now if you understand my problem for my explanation, but thanks anyway for any suggestion!! 如果您能理解我的问题,我现在就不理解了,但是无论如何,谢谢您的建议!
PD: Sorry for my english skills. PD:对不起,我的英语能力。
Your code should be that in classes : 您的代码应该是在类中的代码:
A.php a.php只会
<?php
namespace foo;
class A {
private $a;
public function __construct($a) {
$this->a = $a;
}
}
B.php B.php
<?php
namespace foo;
class B extends A {
private $b;
public function __construct($a, $b) {
parent::__construct($a);
$this->b = $b;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.