gpt4 book ai didi

特征的 PHP instanceof

转载 作者:IT王子 更新时间:2023-10-28 23:46:27 26 4
gpt4 key购买 nike

检查类是否使用特定特征的正确方法是什么?

最佳答案

虽然没有什么能阻止您使用方法来确定类是否使用特征,但推荐的方法是将特征与接口(interface)配对。所以你有:

class Foo implements MyInterface
{
use MyTrait;
}

其中 MyTraitMyInterface 的实现。

然后你检查接口(interface)而不是像这样的特征:

if ($foo instanceof MyInterface) {
...
}

你也可以输入提示,这是你不能用特征做的:

function bar(MyInterface $foo) {
...
}

如果您绝对需要知道某个类是否使用了某个 trait 或实现,您只需向接口(interface)添加另一个方法,该方法会根据实现返回不同的值。

关于特征的 PHP instanceof,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36515677/

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