是否可以在运行时将特质添加到PHP中的类? [英] is it possible to add traits to a class in PHP in runtime?

查看:79
本文介绍了是否可以在运行时将特质添加到PHP中的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个简单的问题,是否可以在不使用eval的情况下在运行时向php类动态添加特征?

Simple question, is it possible to dynamically add traits to a php class in runtime without using eval?

推荐答案

正如Glavic所说,您不能不使用eval()或反射黑客(而且我甚至不确定).

As Glavic said, you can't without using eval() or reflection hacks (and I'm not even sure about that).

但是您真正需要的可能性很小.

But it's very unlikely you really need to.

通过动态类组合(将具有某些功能的类组合成另一个类),您可以取得很多成就.这只是将对具有所需功能的类的引用放入宿主类中的变量中的问题.

You can achieve a lot with dynamic class composition (composing a class with some functionality you want into another class). That's simply a matter of putting a reference to the class with the desired functionality into a variable in the hosting class.

class SomeClassWithNeededFunctionality {}

class SomeClassThatNeedsTheFunctionalityOfTheOtherClass {
    private $serviceClass = NULL;

    public function __construct (SomeClassWithNeededFunctionality $serviceClass) {
        $this -> serviceClass = $serviceClass;
    }
}

这篇关于是否可以在运行时将特质添加到PHP中的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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