title: PHP overriding method of an object
body: <p>Let's say I have an object of type A, looking like this:</p>
  
  <pre><code>class A{
  
      private $item;
  ...
  ...
  ...
  ...
      public function getItem(){
          return $this-&gt;item;
      }
  }
  
  
  $obj = new A();
  </code></pre>
  
  <p>is there any way, that without modifying source code of class A I can <strong>override method <code>getItem</code> only for object <code>$obj</code>?</strong></p>
  
  <p>if yes, then how? </p>
  
  <p>I tried to do it like in code below:</p>
  
  <pre><code>class A{
  
      private $item = 5;
      public function getItem(){
          return $this-&gt;item;
      }
  }
  
  
  $obj = new A();
  
  echo $obj-&gt;getItem();
  
  $obj-&gt;getItem = function(){return 10;};
  
  echo $obj-&gt;getItem();
  </code></pre>
  
  <p>but <a href="https://3v4l.org/7YKZH" rel="nofollow noreferrer">it returns</a> result of original <code>getItem</code> method twice</p>
  
  <p>The thing I want to achieve is <em>replace</em> method I want only in some objects, don't want to modify base class</p>
  
  <p>@EDIT</p>
  
  <p>I played with code a little bit and found something interesting:</p>
  
  <pre><code>&lt;?php
  
  class A{
  
      private $item = 5;
      public function getItem(){
          return $this-&gt;item;
      }
  }
  
  
  $obj = new A();
  
  echo $obj-&gt;getItem()."\n";
  
  $obj-&gt;getItem = function(){return 10;};
  
  echo $obj-&gt;getItem()."\n";
  
  $fun = $obj-&gt;getItem;
  
  echo $fun()."\n";
  </code></pre>
  
  <p><a href="https://3v4l.org/HRe8Q" rel="nofollow noreferrer">this code prints</a> <code>5 5 10</code>, so something in object has changed, but why it isn't a method? Is it impossible to <code>replace</code> method like that?</p>