如何在php-class中获得使用过的特征? [英] how to get used traits in php-class?

查看:56
本文介绍了如何在php-class中获得使用过的特征?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP(5.4)中是否有任何函数可以将使用过的特征作为数组或类似形式获得

Is there any function in PHP (5.4) to get used traits as array or similar:

class myClass extends movingThings {
  use bikes, tanks;

  __construct() {
    echo 'I\'m using the two traits:' . ????; // bikes, tanks
  }
}

推荐答案

要轻松获得使用过的特征,可以调用 class_uses()

To easily get the used traits you can call class_uses()

$usedTraits = class_uses(MyClass);
// or
$usedTraits = class_uses($myObject);

一般建议

在检查可用功能时,通常建议使用interfaces.要将默认功能添加到接口,请使用traits.这样,您还可以从类型提示中受益.

General recommendations

When checking for available functionality, I would generally recommend to use interfaces. To add default functionality to an interface you would use traits. This way you can also benefit from type hinting.

通过实现接口来强制具有功能的对象,然后使用特征为该接口实现默认代码.

Force an object having functionality by implementing an interface and then use a trait to implement default code for that interface.

class MyClass 
    implements SomeInterface 
{
    use SomeTrait;
}

然后您可以通过以下方式检查界面;

Then you can check the interface by;

$myObject = new MyClass();
if ($myObject instanceof SomeInterface) {
    //...
}

仍然使用类型提示;

function someFunction( SomeInterface $object )
{ 
    //...
}

这篇关于如何在php-class中获得使用过的特征?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆