consider the following:
class A
{
public static function bark()
{ echo 'woof'; }
}
class B extends A
{
public static function speak()
{ echo 'hello'; }
}
A::speak();
// Fatal error: Call to undefined method A::speak()
How is one supposed to extend a class with methods that you need to be globally available within that class with methods that are not yet known, but are loaded at run-time, depending on the flow of your application?
Yes sure we can make traits and put use in the class like:
trait B
{
public static function speak()
{ echo 'hello'; }
}
class A
{
use B;
public static function bark()
{ echo 'woof'; }
}
A::speak();
// hello
- but then
use Bis not called dynamically, hence you will have to update class A with every new trait available - manually. This is absurd, why force developers to break their brain in trying to accomplish something so fundamentally simple?
Does anyone have an idea how this can be done in a clean way? I mean I have seen some impressive methods by using Singletons, namespaces, callbacks and the works, but in each case it requires a lot more code and repetitive programming than what is really needed. Either that or i'm missing the boat completely haha! Thanks in advance, your help will be appreciated and voted generously.
BextendsAit inheritsAs methods butAdoes not extendBso it doesn't inheritBs methods; thereforeB::bark()will work,A::speak()won't - as you've found. This is only an issue with static methods really because they belong to the class rather than any objects instantiated from that class.Emailclass and have some methods in there for validation or whatever. It makes sense for the validation methods to be instance methods as they apply to the email data held in that object. Now, say you want to add a blacklist that will apply to every email object ever instantiated. In that case it makes sense to use a static method. With the static method the blacklist will be held in memory once, for the class, with an instance method every Email object will hold the blacklist in memory.