Calculator and Formatter classes
What if I want to put the Formatter class under test? How can I mock the Calculator dependency if it is hard-coded?

I suggest you put that into a separate public method so that it would be possible for other developers to create a partial mock and test it. It will also be clearer since you start reading the class what its dependencies are.

class Formatter
{
    /**
     * @var Calculator
     */ 
    private $calculator;

    /**
     * @param Calculator $calculator
     * @return $this     
     */
    public function setCalculator(Calculator $calculator)
    {
        $this-&gt;calculator = $calculator;

        return $this;
    }

    /**
     * @return Calculator
     */
    public function getCalculator()
    {
        return $this-&gt;calculator;
    }

    /**
     * @return array
     */
    function getAndFormat ($n)
    {
        $table = $this-&gt;getCalculator()-&gt;doPowTable($n);

        return array_map (function($item) {
            $item['i_factor'] = $item['i'].'_'.$item['factor'];
            return $item;
        }, $table);
    }
}


This way you can either provide a different calculator or a mocked one for testing purposes.

Please consider the example below. It shows how to create a partial mock of the Formatter class to override the Calculator dependency.

$mockedCalculator = $this-&gt;getMock(Calculator::class);

// set your mocked calculator behaviour here

$formatter = $this-&gt;getMockBuilder(Formatter::class)
    -&gt;disableOriginalConstructor()
    -&gt;setMethods(['getCalculator'])
    -&gt;getMock();

$formatter
    -&gt;expects($this-&gt;once())
    -&gt;method('getCalculator')
    -&gt;willReturn($mockedCalculator);

$n = 123; // it's just an example
$this-&gt;assertEquals($expectedValue, $formatter-&gt;getAndFormat($n));