我一直认为命名空间的主要目标是防止名称冲突和歧义.
来自php.net的名称空间修复了#1问题:
命名您创建的代码与内部PHP类/函数/常量或第三方类/函数/常量之间的冲突.
但是,大多数语言以某种方式实现"use"关键字别名或将其他命名空间导入当前命名空间.我知道它是如何工作的,但我不明白为什么会使用这种功能.
是否有效地使用'use'关键字来破坏名称空间的目的?
namespace core\utils;
class User {
public static function hello(){
return "Hello from core!";
}
}
//---------------------------------------------------
namespace core2\utils;
class User {
public static function hello(){
return "Hello from core2!";
}
}
//---------------------------------------------------
namespace core2;
//causes name collision, we now have two different classes of type 'utils\User'
use core\utils; //without this line the result is 'Hello from core2'
class Main {
public static function main(){
echo utils\User::hello();
}
}
Main::main();
//outputs Hello from core!
?>
Run Code Online (Sandbox Code Playgroud)
我是否遗漏了某些内容,或者使用"使用"关键字一般不鼓励? …