monkey patching in php

前端 未结 5 1909
悲&欢浪女
悲&欢浪女 2021-01-05 03:49

I\'m trying to figure out how monkey patching works and how I can make it work on my own objects/methods.

I\'ve been looking at this lib, it does exactly what I want

5条回答
  •  醉酒成梦
    2021-01-05 04:01

    As of PHP 5.6, there's still no support for monkey patching; however PHP 5.3 introduced anonymous functions. This answer is not exactly what you're looking for and could probably be improved upon, but the general idea is to use arrays, anonymous functions, and references to create a self-contained, self-referential array (an "object", if you will):

    test.php

    $inner = require('test2.php');
    $inner['say'](); // Hi!
    
    $inner['data']['say'] = 'Bye!';
    $inner['say'](); // still says Hi!
    
    $inner['set_say']('Bye!');
    $inner['say'](); // Bye!
    
    $inner = require('test2.php');
    $inner['say'](); // Hi!
    

    test2.php

    $class = array(
        'data' => array(
            'say' => 'Hi!'
        ),
    
        'say' => function() use (&$class){
            echo $class['data']['say'].'
    '; }, 'set_say' => function($msg) use (&$class){ $class['data']['say'] =& $msg; } ); return $class;

    Also, here's a disclaimer saying that the above code (along with monkey patching in PHP) is almost always a terrible idea, but there are times where this is absolutely necessary.

提交回复
热议问题