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?