In PHP, if a static attribute is defined in the parent class, it cannot be overridden in a child class. But I’m wondering if there’s any way around this.
I’m trying to write a wrapper for someone else’s (somewhat clunky) function. The function in question can be applied to lots of different data types but requires different flags and options for each. But 99% of the time, a default for each type would suffice.
It would be nice if this could be done with inheritance, without having to write new functions each time. For example:
class Foo { public static $default = 'DEFAULT'; public static function doSomething ($param = FALSE ) { $param = ($param === FALSE) ? self::$default : $param; return $param; } } class Bar extends Foo { public static $default = 'NEW DEFAULT FOR CHILD CLASS'; } echo Foo::doSomething() . '\n'; // echoes 'DEFAULT' echo Bar::doSomething() . '\n'; // echoes 'DEFAULT' not 'NEW DEFAULT FOR CHILD CLASS' // because it references $default in the parent class :(
Classic example of why using statics as globals (functions in this case) is a bad idea no matter the language.
The most robust method is to create multiple implementation sub classes of an abstract base ‘Action’ class.
Then to try and remove some of the annoyance of instantiating an instance of the class just to call it’s methods, you can wrap it in a factory of some sort.
For example:
Then create a factory to ‘aid’ in instantiation of the function
Then use it as: