php - 'use' 或 'using' 在编程语言中的用法

标签 php namespaces

我一直认为命名空间的主要目标是防止名称冲突和歧义。

#1 问题由来自 php.net 的命名空间修复:

Name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.

但是,大多数语言都以某种方式实现“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!
?>

我是不是遗漏了什么或者是否真的普遍不鼓励使用“使用”关键字?

无论哪种方式,在什么情况下牺牲封装实际上是个好主意?

以前用use,现在不知道什么时候用use。

编辑: 好吧,让我直截了本地说:如果我使用“use”来获取短名称,这比仅在全局命名空间中声明类更好吗?见下文:

namespace core\utils\longname {    
    class User {} //declare our class in some namespace
}

//------------------Other File---------------------------
namespace { //in another file import our long name ns and use the class
    use core\utils\longname\User as User;
    new User();
}

^ 像这样的命名空间相对于此声明的优势是什么:

namespace {    
    class User {} //declare our class in global namespace
}

//------------------Other File---------------------------
namespace { //in another file just use the class
    new User();
}

两者有什么区别吗?

最佳答案

+1 非常有趣的问题

我的意见

关键词use想象中有如此多的用途和功能

use core\utils\sms\gateway\clickatell\http\SmsSender  as SmsCSender 
use core\utils\sms\gateway\fastSMS\ftp\Smssender as SmsFSender 

现在比较

if(!SmsCSender::send($sms))
{
    SmsFSender::send($sms);
}

if(!core\utils\sms\gateway\clickatell\http\SmsSender::send($sms))
{
    core\utils\sms\gateway\fastSMS\ftp\SmsSender::send($sms);
}

结论

没有namespaceuse我将无法获得如此清晰可读的代码,所以我认为 namespace and use complement each other而不是“使用”破坏命名空间的目的

关于php - 'use' 或 'using' 在编程语言中的用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10062987/

相关文章:

c++ - 为什么命名空间不能是模板参数?

php - Android 移动应用程序与 Web 主机数据库的连接

java - 试图了解什么是 Java 中的命名空间

php - CakePHP 模型加载需要一段时间

php - 如何禁用WordPress的小部件 block 编辑器?

c++ - 命名空间编译问题

Python:什么是 'from import * safe' 模块?

c++ - 命名空间中的未命名空间

php - 为什么我的数据库表在此查询后没有更新?

php - 为什么我不能在 PHP 中回显数据库中的信息?