0

I've already read Why does PHP 5.2+ disallow abstract static class methods? and How to force an implementation of a protected static function - the second is very similar to my case - but I am still without answer. Basically, I want to assure, that every child of my abstract class has implementation of protected static method, without implementing it as this has no meaning and because of lack of key informations there. Also, it must be static (because caller method is static and it has no context) and protected (so I cannot use interface, and I do not want anyone to call it directly), and it will be called by late static binding. Any ideas?

Dummy code below to illuminate my case:

abstract class BaseClass {

    public static function foo() {
        // some common stuff
        static::bar();
        // rest of common stuff
    }

    public function whoooaaa($condition) {
        if ($condition) {
            AClass::foo();
        } else {
            BClass::foo();
        }
    }
}

class AClass extends BaseClass {

    protected static function bar() {
        // do something
    }
}

class BClass extends BaseClass {

    protected static function bar() {
        // do something else
    }
}

// end somewhere else in my code, two constructions, both used:
AClass::foo();
// ....
$baseClassInheritedInstance->whoooaaa($variableCondition);

My only solution, ugly one, is to implement dummy protected static method in base class and throw a generic exception, so that it must be implemented by inheritance.

Community
  • 1
  • 1
  • The example is very dummy obviously, the construction I need to use is very complex, for example, common code in BaseClass::foo contains some loops and conditions, so there is no simple way to refactor it. – Astinus Eberhard Dec 28 '15 at 14:10
  • Also, in the most cases, I would like to use BaseClass::foo or static equivallent of BaseClass::whoooaaa to play with inheritance in static way for shorthand ;) – Astinus Eberhard Dec 28 '15 at 14:18
  • The real question here is: why in the name of Goku are you creating a static inheritance relationship? Isn't there a better way of doing it? – Henrique Barcelos Dec 30 '15 at 17:31
  • Can you please explain an actual use-case? To be honest I cannot possibly imagine a single case where such construct could be useful. – Aleksander Wons Jan 02 '16 at 16:38

1 Answers1

0

You can add a static factory that will fill context for casual objects.

class Factory() {
    public static getObject($condition) {
        $object = $condition ? new A() : new B();
        // you can fill context here and/or use singleton/cache
        return $object;
    }
}

abstract class Base {
    abstract function concreteMethod();
}

class A extends Base {...}
class B extends Base {...}
Ostin
  • 1,511
  • 1
  • 12
  • 25