PHP:在类定义中使用'use'

Seb*_*ski 54 php oop namespaces multiple-inheritance

最近我遇到了一个use在类定义中使用语句的类.

有人可以解释它到底做了什么 - 因为我找不到任何有关它的信息.

我理解它可能是一种将它从给定文件的全局范围移开的方式,但它是否也允许给定的类继承多个父类 - 因为extends只允许一个父类引用?

我看到的例子是Laravel原始安装的User模型:

<?php

use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;

class User extends Eloquent implements UserInterface, RemindableInterface {

    use UserTrait, RemindableTrait;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = array('password', 'remember_token');

}
Run Code Online (Sandbox Code Playgroud)

我已经看到这个模型的一些例子实际上使用了UserTrait类中包含的方法- 因此我怀疑,但我真的想了解更多关于所附use语句的含义.

PHP文档说:

use关键字必须在文件的最外层范围(全局范围)或命名空间内声明中声明.这是因为导入是在编译时完成的,而不是运行时,所以它不能是块作用域.以下示例将显示use关键字的非法使用:

然后是例子:

namespace Languages;

class Greenlandic
{
    use Languages\Danish;

    ...
}
Run Code Online (Sandbox Code Playgroud)

这表明它是use关键字的错误使用- 任何线索?

小智 40

它们被称为Traits,自PHP 5.4开始提供.它们使用use关键字导入到另一个类或命名空间,自PHP 5.0以来,它包括将常规类导入另一个类.它们是单一遗传.实现特征的主要原因是单个继承的限制.

有关更多详细信息,请参阅PHP特性手册: