Overriding an instance method without inheritance in PHP?
<p>Ok, i know that probably this is not possible, but i'll give it a try. Maybe my knowledge is not so good. Please don't downvote, this is just for curiosity and this maybe due to a poor OO design.</p>

<p>Assume that class definition for <code>A</code> is:</p>

<pre><code>class A
{
    public function build()
    {
        $data = $this-&gt;fetchData();
        ...
    }

    public function fetchData()
    {
        // Database eavy query
        return $this-&gt;repository-&gt;fetchDataForCharting();
    }
}
</code></pre>

<p>And then, without using a good and decent OO design, you create class <code>B</code> which is going to use <code>fetchDataForCharting</code> from the repository, for doing some other different calculations:</p>

<pre><code>class B
{
    public $data;

    public function getMonthlyLimit()
    {
        // Database eavy query
        $data = $this-&gt;getData();
    }

    public function getData()
    {
        return isset($this-&gt;data) ? $this-&gt;data :
            $this-&gt;repository-&gt;fetchDataForCharting();
    }
}
</code></pre>

<p>Sometimes you need only <code>A</code>, sometimes you need only <code>B</code>, sometimes both. Is there any way of overriding <code>fetchData</code> at runtime? I mean someting like <code>$.extend()</code> in jQuery:</p>

<pre><code>$b = new B();
$b-&gt;getMonthlyLimit(); // $b-&gt;data filled

$a = new A();

// Override fetchData
$a = extend($a, 'fetchData', function() use($b) { return $b-&gt;data; });

$a-&gt;build(); // Just 1 query
</code></pre>
