【发布时间】:2014-11-02 03:50:34
【问题描述】:
我有一个像这样的类结构(树):
- garcha/
| - html/
| Tag.php
| VTag.php
| etc..
工作原理:(由 spl_autoload_register 自动加载)
use garcha\html;
$tag = new html\Tag('a');
不能工作:
use garcha\html;
$tag = new Tag('a');
没有实现它:(我不想逐行写每个类文件的use语句,指向类目录并使用没有父命名空间的类)
use garcha\html\Tag;
use garcha\html\VTag;
...
我不喜欢这种方式,因为它很无聊,需要更多时间,不够灵活(你可以更改文件结构、类名等。)
简而言之:我正在尝试自动加载命名空间的类目录并在其中使用具有非限定名称的类。
自动加载功能:
class AutoLoader
{
protected static $pathes = array();
/**
* add pathes
*
* @param string $path
*/
public static function addPath($path)
{
$path = realpath($path);
if ($path)
{
self::$pathes[] = $path . DIRECTORY_SEPARATOR;
}
}
/**
* load the class
* @param string $class
* @return boolean
*/
public static function load($class)
{
$classPath = $class.'.php'; // Do whatever logic here
foreach (self::$pathes as $path)
{
if (is_file($path . $classPath))
{
require_once $path . $classPath;
return true;
}
}
return false;
}
}
添加路径:
AutoLoader::addPath(BASE_PATH.DIRECTORY_SEPARATOR.'vendor');
自动加载有效,问题是如何处理
use garcha\html; // class directory
并使用不带前导 html 的类
$tag = new Tag('p'); // not $tag = new html\Tag('p');
【问题讨论】:
-
您的
self::$pathes设置为什么 -
为什么不使用完整的命名空间路径?以后改路径就得改了,
use与否 -
@Ggio 我更新了问题
-
@Machavity 想象一下该目录中有超过 10 个类,为每个类写 10 行并不酷:/
-
@GeorgeGarchagudashvili 可能会在您的自动加载器中添加
html以从/html加载所有类
标签: php namespaces spl-autoload-register