```
// 注册命名空间定义,也就是文件目录的路径
self::addNamespace([
'think' => LIB_PATH . 'think' . DS,
'behavior' => LIB_PATH . 'behavior' . DS,
'traits' => LIB_PATH . 'traits' . DS,
]);
```
可以看出调用了自身类的addNamespace方法,该方法如下:
```
/**
* 注册命名空间
* @access public
* @param string|array $namespace 命名空间
* @param string $path 路径
* @return void
*/
public static function addNamespace($namespace, $path = '')
{
//var_dump($namespace);
/* array(3) {
["think"]=>
string(58) "C:\phpStudy\PHPTutorial\WWW\ceshi1\thinkphp\library\think\"
["behavior"]=>
string(61) "C:\phpStudy\PHPTutorial\WWW\ceshi1\thinkphp\library\behavior\"
["traits"]=>
string(59) "C:\phpStudy\PHPTutorial\WWW\ceshi1\thinkphp\library\traits\"
}
string(3) "app"
*/
if (is_array($namespace)) {
//若为数组则执行
foreach ($namespace as $prefix => $paths) {
//执行addPsr4方法 为属性$prefixDirsPsr4添加数组成员
self::addPsr4($prefix . '\\', rtrim($paths, DS), true);
}
} else {
//单条则执行
//执行addPsr4方法 为属性$prefixDirsPsr4添加数组成员
self::addPsr4($namespace . '\\', rtrim($path, DS), true);
}
}
```
添加 PSR-4 空间
```
/**
* 添加 PSR-4 空间
* @access private
* @param array|string $prefix 空间前缀
* @param string $paths 路径
* @param bool $prepend 预先设置的优先级更高
* @return void
*/
private static function addPsr4($prefix, $paths, $prepend = false)
{
/*
echo $prefix."<br/>";
think\
behavior\
traits\
app\
*/
/*
echo $paths."<br/>";
C:\phpStudy\PHPTutorial\WWW\ceshi1\thinkphp\library\think
C:\phpStudy\PHPTutorial\WWW\ceshi1\thinkphp\library\behavior
C:\phpStudy\PHPTutorial\WWW\ceshi1\thinkphp\library\traits
C:\phpStudy\PHPTutorial\WWW\ceshi1\public/../application/
*/
if (!$prefix) {
// 为根命名空间注册目录
self::$fallbackDirsPsr4 = $prepend ?
array_merge((array) $paths, self::$fallbackDirsPsr4) :
array_merge(self::$fallbackDirsPsr4, (array) $paths);
} elseif (!isset(self::$prefixDirsPsr4[$prefix])) {
//为新命名空间注册目录
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException(
"A non-empty PSR-4 prefix must end with a namespace separator."
);
}
self::$prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
self::$prefixDirsPsr4[$prefix] = (array) $paths;
} else {
//首先执行这里
self::$prefixDirsPsr4[$prefix] = $prepend ?
// Prepend directories for an already registered namespace.
array_merge((array) $paths, self::$prefixDirsPsr4[$prefix]) :
// Append directories for an already registered namespace.
array_merge(self::$prefixDirsPsr4[$prefix], (array) $paths);
}
}
```
