gpt4 book ai didi

php - 多个特征同时使用相同的基本特征

转载 作者:可可西里 更新时间:2023-10-31 22:53:10 24 4
gpt4 key购买 nike

好吧,假设存在以下问题:

trait Base
{
public function doSomething()
{
// Do fancy stuff needed in other traits
}
}

trait A
{
use Base;

public function foo()
{
// Do something
}
}


trait B
{
use Base;

public function bar()
{
// Do something else
}
}

现在我想实现一个同时使用特征 AB 的类:

class MyClass
{
use A, B;
}

PHP 告诉我它不能重新定义函数 doSomething()。 PHP 无法检测到 AB 共享同一个特征并且不将其复制到 MyClass 中的原因是什么(它是阻止我编写不干净代码的错误还是功能)?

对于我的问题,是否有比我最终采用的解决方法更好的解决方案:

trait Base
{
public function doSomething()
{
// Do fancy stuff needed in other traits
}
}

trait A
{
abstract function doSomething();

public function foo()
{
// Do something
}
}


trait B
{
abstract function doSomething();

public function bar()
{
// Do something else
}
}

然后是我的课:

class MyClass
{
use Base, A, B;
}

最佳答案

你可以像这样用“insteadof”来解决这个冲突:

class MyClass
{
use A, B {
A::doSomething insteadof B;
}
}

编辑对于更多的特征,解决冲突可以是这样的:

class MyClass
{
use A, B, C, D {
A::doSomething insteadof B, C, D;
}
}

关于php - 多个特征同时使用相同的基本特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31962986/

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