lea*_*php 6 php namespaces traits
从PHP文档:
命名空间只影响四种类型的代码:类,接口,函数和常量.
但是,在我看来,TRAITS也受到影响:
namespace FOO;
trait fooFoo {}
namespace BAR;
class baz
{
use fooFoo; // Fatal error: Trait 'BAR\fooFoo' not found in
}
Run Code Online (Sandbox Code Playgroud)
我错了吗?
对,他们是。
use在类外部导入特征以进行 PSR-4 自动加载。
然后use是类中的特征名称。
namespace Example\Controllers;
use Example\Traits\MyTrait;
class Example {
use MyTrait;
// Do something
}
Run Code Online (Sandbox Code Playgroud)
或者只是use具有完整命名空间的 Trait:
namespace Example\Controllers;
class Example {
use \Example\Traits\MyTrait;
// Do something
}
Run Code Online (Sandbox Code Playgroud)
我认为他们也受到影响。查看php.net 页面上的一些评论。
第一条评论:
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
}
?>
Run Code Online (Sandbox Code Playgroud)