【问题标题】:Are traits in PHP affected by namespaces?PHP 中的特征是否受命名空间的影响?
【发布时间】:2013-11-03 05:12:08
【问题描述】:

来自 PHP 文档:

只有四种类型的代码受命名空间影响:类、接口、函数和常量。

但是,在我看来,TRAITS 也会受到影响:

namespace FOO;

trait fooFoo {}

namespace BAR;

class baz
{
    use fooFoo; // Fatal error: Trait 'BAR\fooFoo' not found in
}

我错了吗?

【问题讨论】:

  • 他们似乎是这样放完整路径并以“\”开头使用\FOO\fooFoo;

标签: php namespaces traits


【解决方案1】:

是的,他们是。

在类外导入带有use 的特征以进行 PSR-4 自动加载。

然后use 类中的特征名称。

namespace Example\Controllers;

use Example\Traits\MyTrait;

class Example {
    use MyTrait;

    // Do something
}

或者只是 use 具有完整命名空间的特征:

namespace Example\Controllers;

class Example {
    use \Example\Traits\MyTrait;

    // Do something
}

【讨论】:

    【解决方案2】:

    我认为他们也受到影响。看一些cmetson the php.net page

    第一条评论:

    Note that the "use" operator for traits (inside a class) and the "use" operator for namespaces (outside the class) resolve names differently. "use" for namespaces always sees its arguments as absolute (starting at the global namespace):
    
    <?php
    namespace Foo\Bar;
    use Foo\Test;  // means \Foo\Test - the initial \ is optional
    ?>
    
    On the other hand, "use" for traits respects the current namespace:
    
    <?php
    namespace Foo\Bar;
    class SomeClass {
        use Foo\Test;   // means \Foo\Bar\Foo\Test
    }
    ?>
    

    【讨论】:

      【解决方案3】:

      根据我的经验,如果您粘贴的这段代码位于不同的文件/文件夹中,并且您使用 spl_autoload_register 函数加载您需要这样做的类:

        //file is in FOO/FooFoo.php
        namespace FOO;
        trait fooFoo {}
      
        //file is in BAR/baz.php
        namespace BAR;
        class baz
        {
         use \FOO\fooFoo; // note the backslash at the beginning, use must be in the class itself
        }
      

      【讨论】:

        【解决方案4】:

        文档还说“A Trait is similar to a class”, 特征是类的特例。 因此,适用于类的内容也适用于特征。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-11-28
          • 2012-09-25
          • 2019-11-20
          • 1970-01-01
          • 2011-08-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多