1

Consider the following parent class Parent.php:

class Parent {

    protected static $className;

    public static function __static() {
        static::$className = get_called_class();
    }

    public static function doSomething1() { ... }
    public static function doSomething2() { ... }
    public static function doSomething3() { ... }
}
Parent::__static();

and its child class Child.php:

class Child extends Parent { }

Each method doSomething 1-3 needs to access $className. If Child calls doSomething1(), the $className must be Child, and not Model. I could certainly do

public static function doSomething() { $className = get_called_class(); }

in every method but this would result in code repetition. Plus, $className makes most sense to be declared static. The workaround I used is to call a static class initializer after class declaration in Parent. Obviously this didn't work either, because the variable $class is still initilized on Parent, not on Child, despite the use of static (i.e. late binding).

Long story short, how do I get the following:

Child::doSomething1(); // -> $className must be 'Child'
Child::doSomething2(); // -> $className must be 'Child'
Child::doSomething3(); // -> $className must be 'Child'

Let me complicate it a little bit: I have multiple child classes, Child1, Child2, Child3, so placing ChildX::__static(); at the end of file in each ChildX class would be inefficient.

BONUS: if I call doSomething1() in Child1, does that mean that Child2 and Child3 will share a static property $className with the value Child1? My guess is no, but I'd love to hear your viewpoint.

Any thoughts on this?

Community
  • 1
  • 1
Alex
  • 3,719
  • 7
  • 35
  • 57
  • http://stackoverflow.com/questions/1280492/extending-php-static-classes – i-- Nov 09 '16 at 05:15
  • @i-- It would be a bit inefficient to redeclare `get_class_name` in every single child... What if I have 10 of them? In fact, in my project, the child is a model, and the parent is a model base class – Alex Nov 09 '16 at 05:18

0 Answers0