【问题标题】:Aliasing with a name similar to a class name使用类似于类名的名称进行别名
【发布时间】:2014-04-02 09:02:49
【问题描述】:

在php.net中有一个我没看懂的例子:

<?php
namespace foo;
use My\Full\Classname as Another;

// this is the same as use My\Full\NSname as NSname
use My\Full\NSname;

// importing a global class
use ArrayObject;

$obj = new namespace\Another; // instantiates object of class foo\Another
$obj = new Another; // instantiates object of class My\Full\Classname
NSname\subns\func(); // calls function My\Full\NSname\subns\func
$a = new ArrayObject(array(1)); // instantiates object of class ArrayObject
// without the "use ArrayObject" we would instantiate an object of class foo\ArrayObject
?>

从这里:http://www.php.net/manual/en/language.namespaces.importing.php

他们怎么能在这个声明$obj = new namespace\Another; 中说它从类foo\another 中实例化一个对象?当我尝试向 Another 类添加定义时,我收到一个错误,提示另一个名称已在使用中(因为它是别名)。

【问题讨论】:

    标签: php class namespaces alias


    【解决方案1】:

    如果foo\Another 类是在另一个没有此类别名的文件中定义的,则此方法有效。

    另一个.php

    <?php
    
    namespace foo;
    
    class Another { }
    

    test.php

    <?php
    
    namespace foo;
    use My\Full\Classname as Another;
    
    require_once 'another.php';
    
    new namespace\Another;
    

    给出的示例是为了说明命名空间解析,并方便地忽略可能出现的其他细节和冲突。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-05
      • 2022-12-15
      • 2018-05-05
      • 1970-01-01
      相关资源
      最近更新 更多