gpt4 book ai didi

php - 为什么 trait 不覆盖类中的方法?

转载 作者:行者123 更新时间:2023-12-03 21:19:28 25 4
gpt4 key购买 nike

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

<?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

我认为这很清楚,所以现在让我们使用 Trait:
<?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 方法覆盖了基类方法。现在让我们在 B 类中创建一个 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.

关于php - 为什么 trait 不覆盖类中的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28453941/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com