PHP: Workaround to reuse modified private parent method

Viewed 64

I like to modify one private method of an inherited class.

These are my requirements:

  • I can't modify the parent class.
  • I have to reuse the code of the inherited class.
  • I need to append some code before the parent's private method code.

Basically I like this code

<?php

class ParentClass
{
    public function doStuff()
    {
        echo 'Doing parent stuff';

        $this->doPrivateStuff();

        echo 'Doing more parent stuff';
    }

    private function doPrivateStuff()
    {
        echo 'Doing private stuff';
    }
}

class ChildClass extends ParentClass
{
    private function doPrivateStuff()
    {
        echo 'Additional code';

        parent::doPrivateStuff();
    }
}

$obj = new ChildClass;
$obj->doStuff();

?>

to output

Doing parent stuff
Additional code
Doing private stuff
Doing more parent stuff

instead of

Doing parent stuff
Doing private stuff
Doing more parent stuff

I know that my code "fails" because doPrivateStuff is a private method.

What's the best workaround to reuse a modified version of the private method anyway?

PS:

My current workaround is to implement the methods doStuff and doPrivateStuff in my ChildClass by parsing the parent's methods' bodies via reflection and evaluating them.

I don't exactly consider this a "clean" approach, ahem. So I'm happy to read your recommendations.

1 Answers

Do this :

<?php

class ParentClass
{
    public function doStuff()
    {
        // Some code

        $this->doPrivateStuff();

        // More code
    }

    private function doPrivateStuff()
    {
        echo 'Doing private stuff';
    }
}

class ChildClass extends ParentClass
{
    public function doStuff()
    {
        echo 'Additional code';

        parent::doStuff();
    }
}

$obj = new ChildClass;
$obj->doStuff();

?>
Related