dopnpoh056622 2019-05-21 14:18
浏览 75

动态创建一个实现任意接口的类

I'm creating a PHP library to extract schema.org structured data out of web pages.

Schema.org features a multiple inheritance hierarchy that I can only achieve through PHP interfaces:

interface LocalBusiness extends Organization, Place
{
}

In addition to that, schema.org allows an object to be of multiple independent types, for example it can be both a Book and a Product, and use properties from both:

<!-- Uses both the "Book" and "Product" item types -->
<div vocab="http://schema.org/" resource="#record" typeof="Book Product">
...
<span property="author">
...
<span property="sku">

To support this use case, I need to dynamically generate classes that implement more than one interface. In the example above, this could look like:

new class implements Book, Product
{
  use BookTrait;
  use ProductTrait;
}

I can obviously not generate all interface combinations ahead of time, so I'm thinking of a way to generate such an implementation at runtime.

As far as I know, reflection does not allow to do this kind of things, so the only way I can think of is using generated code and eval(), like mocking libraries do. The problem is, eval() can be disabled, which is an issue when writing a general-purpose library.

Did I overlook something? Is there another way to dynamically create an object that implements an arbitrary number of interfaces, that are only known at runtime?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 树莓派与pix飞控通信
    • ¥15 自动转发微信群信息到另外一个微信群
    • ¥15 outlook无法配置成功
    • ¥30 这是哪个作者做的宝宝起名网站
    • ¥60 版本过低apk如何修改可以兼容新的安卓系统
    • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
    • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
    • ¥50 有数据,怎么用matlab求全要素生产率
    • ¥15 TI的insta-spin例程
    • ¥15 完成下列问题完成下列问题