DEV Community

Discussion on: Traits are not inherited

Collapse
 
bdelespierre profile image
Benjamin Delespierre • Edited

That actually makes sense. The static property belongs to the trait so changing its value will effectively change it from every using class' perspective.

As a seasonned PHP developper, I would advise you to avoid static as much as possible. Rules of static inheritance in PHP are difficult to understand and the staticness will make your code more rigid. Use dependency injection instead.

Want an example? PHP will let you write this monstruosity:

class A
{
    public funciton foo()
    {
        return static::bar();
    }

    abstract protected static function bar();
}

class B extends A 
{
    protected static function bar()
    {
        return "Hello!";
    }
}

B::foo(); // Hello!
Enter fullscreen mode Exit fullscreen mode
Collapse
 
doekenorg profile image
Doeke Norg

Hi @bdelespierre , I'm not quite sure what you mean. The static property on the trait does not change it on every class using it; that was the point of this post :-) But maybe I'm misunderstanding your comment.

I do somewhat agree on your point of view of static methods. They should be used sparingly, albeit only for the testing hell. And although singletons have their time and place; dependency injection is preferred almost always. But singletons are only one use-case of static methods of course :-)

I think some people have a hard time grasping the difference between static and non-static when it comes to classes or instances of those classes. I think proper education is key in using these concepts to your benefit. And I hope a post like this contributes to that end :-)

Thank you for your comment and insights!