为什么 trait 不覆盖 class 中的方法?

Why trait does not override method in class?

我想知道我的 php 解释器是否无法正常工作,或者我对 Traits 的理解有误。这是我的一段代码:

<?php

trait ExampleTrait{
    public function foo()
    {
        echo 'y';
    }
}

class ExampleClass
{
    use ExampleTrait;

    public function foo()
    {
        echo 'x';
    }
}

$exCl = new ExampleClass();

$exCl->foo();

我假设这应该显示 "y",但它显示 "x"。为什么?

仔细阅读 Trait documentation 我建议尝试每个示例并进行自己的修改以确保您理解它。这是我的例子,希望对你有帮助:

<?php
class A {
    public function foo() {
        echo "x";
    }
}

class B extends A {}

$test = new B();
$test->foo();

// result X

我认为这很清楚,所以现在让我们使用一个特征:

<?php
class A {
    public function foo() {
        echo "x";
    }
}

trait T {
    public function foo() {
        echo "y";
    }
}

class B extends A {
    use T;
}

$test = new B();
$test->foo();

// result y

如您所见,Trait 方法覆盖了基础 class 方法。现在让我们在 B class

中创建一个 foo 方法
<?php
class A {
    public function foo() {
        echo "x";
    }
}

trait T {
    public function foo() {
        echo "y";
    }
}

class B extends A {
    use T;
    public function foo() {
        echo "z";
    }
}

$test = new B();
$test->foo();

// result z

An inherited member from a base class is overridden by a member inserted by a Trait. The precedence order is that members from the current class override Trait methods, which in turn override inherited methods.