Steve Steve - 6 days ago 6
PHP Question

Change parent class method behavior, based on extended class (static)

I have a static class that includes various private functions. These are called by a public function. I would like to allow the option of changing one of the private functions. Either using an extended class or in some other way.

Here's my current attempt which isn't working but hopefully demonstrates what I'm trying to achieve.

class OriginalClass {

public static function go()
{
self::doThis();
self::doThat();
self::doOther();
}

private static function doThis()
{
echo 'this' . PHP_EOL;
}

private static function doThat()
{
echo 'that' . PHP_EOL;
}

private static function doOther()
{
echo 'default' . PHP_EOL;
}
}

class ExtendedClass extends OriginalClass {

private static function doOther()
{
echo 'other' . PHP_EOL;
}
}

ExtendedClass::go();


What I would like to get is

this
that
other


but I'm getting

this
that
default


I want
OriginalClass
to be able to be used as is, but I would like to give the option of being able to change what
doOther()
does. I don't mind how, I'm just trying to keep the code clean and not do anything hacky.

Any ideas?

Answer

doOther is a private method in both classes. And private methods are not accessible anywhere except class, where they are defined.

So doOther of ExtendedClass context is not accessible from OriginalClass context. That's why go method can't access ExtendedClass::doOther, so it search for doOther in a OriginalClass which exists.

So, what changes should be done:

  1. ExtendedClass::doOther should be at least protected to be availble in OriginalClass context.

  2. self keyword refers to class OriginalClass, use late static binding to get the name of a real class which calls for method


class OriginalClass {

    public static function go()
    {
        self::doThis();
        self::doThat();
        static::doOther();  // keyword `static`
    }

    private static function doThis()
    {
        echo 'this' . PHP_EOL;
    }

    private static function doThat()
    {
        echo 'that' . PHP_EOL;
    }

    private static function doOther()
    {
        echo 'default' . PHP_EOL;
    }
}

class ExtendedClass extends OriginalClass {

    protected static function doOther() // `protected` visiblity
    {
        echo 'other' . PHP_EOL;
    }
}

ExtendedClass::go();
// output:
// this
// that
// other

OriginalClass::go();
// this
// that
// default
Comments