美文网首页
php的猴子补丁,动态改变函数和类方法,需要runkit扩展

php的猴子补丁,动态改变函数和类方法,需要runkit扩展

作者: sorry510 | 来源:发表于2019-12-04 16:03 被阅读0次

安装

php5版本扩展下载地址https://pecl.php.net/package/runkit/1.0.4/windows
php7版本下载地址https://pecl.php.net/package/runkit7/3.0.0/windows因为原作者不开发了,被别人已接手

使用方法例子

// 动态修改函数
function test() {
   echo "php";
}

runkit7_function_redefine('test', function($a) {
     echo $a . ' python';
});
test('hello'); // hello python

// 动态修改类的方法
class A {
    public function test() {
        return 'php';
    }
}

runkit7_method_redefine(
    'A',
    'test',
    function ($name = 'hello') {
        return $name . ' python';
    },
    RUNKIT7_ACC_PUBLIC
);

echo (new A())->test(); // hello python

详细文档

https://www.php.net/manual/zh/book.runkit.php
php7需要将runkit_*替换为runkit7_*

runkit7的github地址

https://github.com/runkit7/runkit7

简单封装

构造函数必须接受一个实例类(只有让composer自动加载了这个类文件,才能改变这个类的方法)

class MonkeyPatch
{
  public function __construct($class)
  {
    if (!function_exists('runkit7_method_redefine')) {
      die('runkit extends not find');
    }
    $this->className = get_class($class);
  }

  public function changeMethod($method, Closure $callback, $type = \RUNKIT7_ACC_PUBLIC)
  {
    return runkit7_method_redefine(
      $this->className,
      $method,
      $callback,
      $type
    );
  }
}

// use
$patch = new MonkeyPatch(new A);
$result = $patch->changeMethod('test', function ($name = 'hello') {
        return $name . ' java';
});

相关文章

  • php的猴子补丁,动态改变函数和类方法,需要runkit扩展

    安装 php5版本扩展下载地址https://pecl.php.net/package/runkit/1.0.4/...

  • 猴子补丁的由来

    转:什么是猴子补丁 所谓的猴子补丁的含义是指在动态语言中,不去改变源码而对功能进行追加和变更。猴子补丁的这个叫法起...

  • PHP的反射类ReflectionClass、Reflectio

    PHP5 具有完整的反射API,添加对类、接口、函数、方法和扩展进行反向工程的能力。 反射是什么? 它是指在PHP...

  • Python猴子补丁

    属性在运行时的动态替换,叫做猴子补丁(Monkey Patch)。 为什么叫猴子补丁 属性的运行时替换和猴子也没什...

  • php反射实现Ioc/Di及注解

    ​ PHP5之后提供了完整的反射API,添加了对类、接口、函数、方法和扩展进行反向工程的能力。此外,反...

  • 每天学一点 Kotlin -- 类的进阶:扩展

    1. 扩展 1.1 类的扩展是给类增加新的方法或属性。 2. 扩展类的方法 1.2 扩展的语法:和定义函数差不多,...

  • Python 中的装饰器

    装饰器作用:动态改变函数、方法、类的功能而不用修改被改变对象本身的代码。只需要定义一个装饰器函数,然后给要改变的函...

  • python中一切皆对象

    Python中的元类和猴子补丁都是基于一切皆对象 函数和类也是对象,属于Python的一等公民 类可以直接实例化对...

  • runtime常用方法

    类 类结构 类实例结构 常用函数 方法 结构 类方法的常用函数 方法的常用函数 方法选择器 动态创建类 示例: 动...

  • Kotlin 中缀表达式

    扩展函数 假如有一个类,具有若干个字段(属性)和方法。但是我们想给它添加新的方法,这就可以使用扩展函数了。扩展函数...

网友评论

      本文标题:php的猴子补丁,动态改变函数和类方法,需要runkit扩展

      本文链接:https://www.haomeiwen.com/subject/pwjlgctx.html