如何在运行时生成或修改PHP类? [英] How to generate or modify a PHP class at runtime?

查看:90
本文介绍了如何在运行时生成或修改PHP类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

schmittjoh/cg-library 似乎是我所需要的,但根本没有任何文档.

The schmittjoh/cg-library seems what I need, but there is no documentation at all.

此库提供了一些通常需要生成的工具 PHP代码.它的优势之一在于增强现有功能 具有行为的课程.

This library provides some tools that you commonly need for generating PHP code. One of it's strength lies in the enhancement of existing classes with behaviors.

给出A类:

class A {}

我想在运行时当然使用某种缓存机制类A进行修改,以使其实现给定的接口:

I'd like to modify, at runtime of course and with some cache mechanism, class A, making it implementing a given interface:

interface I
{
    public function mustImplement();
}

...对A类中的方法mustImplement()具有默认"实现.

... with a "default" implementation for method mustImplement() in A class.

推荐答案

注意: OP需要PHP 5.3(之前没有用这种方式标记),这个问题是PHP 5.4的概述.

Note: OP needs PHP 5.3 (it was not tagged that way before), this question is a general outline for PHP 5.4.

您可以通过定义接口并添加包含这些接口的默认实现的特征来实现.

You can do that with defining the interface and adding traits that contain the default implementation for those interfaces.

然后您创建一个新的类定义

Then you create a new class definition that

  • 扩展从您的基类
  • 该接口的
  • 实现
  • 使用默认特征.
  • extends from your base-class,
  • implements that interface and
  • uses the default traits.

有关示例,请参见 PHP –任何现实的例子/最佳实践?

您可以轻松生成该类定义代码,然后直接存储并includeeval.

You can easily generate that class definition code and either store it and include it or eval it straight ahead.

如果使新的类名包含其组成的所有信息(在您的情况下为基类名和接口),则可以防止轻易创建重复的类定义.

If you make the new classname containing all the information it consists of (in your case the base classname and the interface), you can prevent to create duplicate class definitions easily.

这可以在没有任何PHP扩展(例如runkit)的情况下使用.如果您使用serialize进行播放,甚至可以在运行时使用新接口在现有对象上进行重载,以防它们可以序列化/反序列化.

This works without any PHP extension like runkit. If you bring serialize into the play, you can even overload existing objects at runtime with the new interface in case they can serialize / deserialize.

您可以在以下位置找到已实现此功能的代码示例:

You can find a code-example that has been implementing this in:

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