PHP中的特性是否受名称空间的影响?

PHP中的特性是否受名称空间的影响?,php,namespaces,traits,Php,Namespaces,Traits,从PHP文档中: 只有四种类型的代码受名称空间的影响:类、接口、函数和常量 但是,在我看来,性格特征也会受到影响: namespace FOO; trait fooFoo {} namespace BAR; class baz { use fooFoo; // Fatal error: Trait 'BAR\fooFoo' not found in } 我错了吗?我想他们也受到了影响。请看一些评论 第一点意见: Note that the "use" operator for t

从PHP文档中:

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

但是,在我看来,性格特征也会受到影响:

namespace FOO;

trait fooFoo {}

namespace BAR;

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

我错了吗?

我想他们也受到了影响。请看一些评论

第一点意见:

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
}
?>
注意,traits(类内)的“use”操作符和namespace(类外)的“use”操作符解析名称的方式不同。名称空间的“use”始终将其参数视为绝对参数(从全局名称空间开始):
另一方面,traits的“use”表示当前名称空间:

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

  //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
  }
是的,他们是

使用
在类外使用
导入特征以自动加载PSR-4

然后
在类中使用特征名称

namespace Example\Controllers;

use Example\Traits\MyTrait;

class Example {
    use MyTrait;

    // Do something
}
或者只
使用带有完整名称空间的Trait:

namespace Example\Controllers;

class Example {
    use \Example\Traits\MyTrait;

    // Do something
}

文档还说“一个特征类似于一个类”, 特质是一个类的特例。
因此,适用于类的内容也适用于特性。

他们似乎是这样的:把完整的路径放在“\”上,并以“\”use\FOO\FOO;