【问题标题】:Is there a PHP namespace shortcut for this?是否有为此的 PHP 命名空间快捷方式?
【发布时间】:2012-05-15 02:10:55
【问题描述】:

我正在尝试找到一种方法来大量应用这些命名空间,因为这样写出来会很不方便。我知道我可以简单地使用jream\ as j,但我想看看是否可以避免使用反斜杠。

require '../jream/Autoload.php';

use jream\Autoload as Autoload,
    jream\Database as Database,
    jream\Exception as Exception,
    jream\Form as Form,
    jream\Hash as Hash,
    jream\Output as Output,
    jream\Registry as Registry,
    jream\Session as Session;

new Autoload('../jream');

有没有办法按照这些方式说些什么:jream\\* as *;

任何提示将不胜感激:)

【问题讨论】:

    标签: php namespaces


    【解决方案1】:

    至少你可以跳过所有多余的as 别名:

    use jream\Autoload,
        jream\Database,
        jream\Exception,
        jream\Form,
        jream\Hash,
        jream\Output,
        jream\Registry,
        jream\Session;
    

    如果您想使用命名空间中的所有内容而不一一键入,那么确实唯一真正的选择是将命名空间作为一个整体命名并使用反斜杠:

    use jream as j;
    
    new j\Autoload;
    

    【讨论】:

    • 谢谢,这可能是最好的方法。
    【解决方案2】:

    难道没有办法按照以下方式表达:jream\* as *; ?

    不,但你可以这样做:

    // use-jream.php
    class Autoload extends jream\Autoload {}
    class Database extends jream\Database {}
    ...
    
    // index.php
    require_once 'use-jream.php'
    
    new Autoload('../jream');
    

    但我真的不建议这样做。

    当然,如果您只想更改默认命名空间:

    namespace jream;
    
    new Autoload('../jream');
    

    这就是import jream.* 在 PHP 中的全部含义,因为 PHP 绝对无法确定一个类是否可能存在于某个命名空间中,除非您通知它。

    【讨论】:

    • 谢谢你的回答,我喜欢关于设置命名空间的最后一部分!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-30
    • 1970-01-01
    • 2015-10-04
    相关资源
    最近更新 更多