";Trait未找到错误“;与特征的定义顺序和内容有关


"Trait not found error" related to the order of definition and content of the trait

我用这种方式定义了一个PHP文件。

<?php
class A
{
    use T1;
}
trait T1
{
}

一切都按预期进行,直到我以这种方式修改特征T1

<?php
class A
{
    use T1;
}
trait T1
{
    use T2; // Commenting this line the error goes away too.
}
trait T2
{
}

执行php trait.php时,我收到以下错误。

PHP Fatal error:  Trait 'T1' not found in a.php on line 7
Fatal error: Trait 'T1' not found in a.php on line 7
  • 注释use T2;时,错误消失
  • 在特征T2之后移动类A,则错误消失

为什么use T2;会触发此错误

为什么特征的定义顺序很重要


更新1:

我认为这是一个与需要外部文件有关的问题,但这个问题与特征的定义顺序有关。因此,我相应地更新了这个问题。

文档没有直接说明(或者我找不到它),但我认为必须定义一个特征,才能被另一个特征引用。对象及其类也是如此。这是无效的:

  $foo = new Foo();
  class Foo extends Bar
  {
  }
  class Bar
  {
  }

因为"Foo"在使用之前尚未声明。这个有效的,但是:

  class Foo extends Bar
  {
  }
  $foo = new Foo();
  class Bar
  {
  }

尽管看起来不应该一目了然。

奇怪的是,这也是有效的:

  class Foo extends Bar
  {
  }
  $foo = new Foo();
  $bar = new Bar();
  class Bar
  {
  }

由于Foo的声明导致PHP在Bar实例化为$bar之前在文件中搜索Bar

当然,最佳实践是每个文件只定义一个类或特征,使用类Autoloader(它也适用于特征),而不将可运行代码放在这些文件中的类或特征定义之外。