title: monkey patching in php
body: <p>I'm trying to figure out how monkey patching works and how I can make it work on my own objects/methods.</p>
  
  <p>I've been looking at this lib, it does exactly what I want to do myself:
  <a href="https://github.com/antecedent/patchwork" rel="noreferrer">https://github.com/antecedent/patchwork</a></p>
  
  <p>With it you can redefine a method from an object. It uses the 'monkey patch' technique for that. But I couldn't really figure out what exactly is going on by looking at the source.</p>
  
  <p>So suppose I have the following object:</p>
  
  <pre><code>//file: MyClass.php
  namespace MyClass;
  
  class MyClass {
  
      public function say()
      {
          echo 'Hi';
      }
  }
  </code></pre>
  
  <p>I'd like to do something like this:</p>
  
  <pre><code>Monkeypatch\replace('MyClass', 'say', function() {
      echo 'Hello';
  });
  
  $obj = new MyClass();
  $obj-&gt;say();  // Prints: 'Hello'
  </code></pre>
  
  <p>But i'm not sure how to code the actual patching part. I know namespaces in this context are important. But how does that exactly let me patch a certain method? And do I need to use eval() somewhere (if so, how)?</p>
  
  <p>I couldn't really find any good examples about this matter, except:
  <a href="http://till.klampaeckel.de/blog/archives/105-Monkey-patching-in-PHP.html" rel="noreferrer">http://till.klampaeckel.de/blog/archives/105-Monkey-patching-in-PHP.html</a></p>
  
  <p>But I really don't see how I can apply that to my own objects/methods. I'm hoping for a good explanation or example.</p>