最近,我遇到了一个在类定义内使用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');

}

并且我已经看到了该模型的一些示例,这些示例实际上使用了UserTrait类中包含的方法-因此引起了我的怀疑,但我真的很想了解有关附带的use语句的含义的更多信息。

PHP documentation说:



接下来是示例:
namespace Languages;

class Greenlandic
{
    use Languages\Danish;

    ...
}

这将表明它是对use关键字的不正确使用-有任何线索吗?

最佳答案

它们称为特性,自PHP 5.4起可用。它们使用使用关键字导入到另一个类或 namespace 中,该关键字自PHP 5.0起就包含在内,例如将常规类导入另一个类中。它们是单一继承。实现特征的主要原因是由于单一继承的限制。

有关更多详细信息,请参见PHP trait manual:

09-10 04:22
查看更多