DEV Community

Aleson França
Aleson França

Posted on

Understanding Traits in PHP: Reusing Code with Elegance

In PHP, a class can't inherit from more than one other class — multiple inheritance is not allowed. But what if you want to reuse methods in different classes? The answer is traits.

What is a Trait ?

A trait is a way to reuse code in languages that don't support multiple inheritance. It lets you define methods and "inject" them into as many classes as you want, without inheritance.


Example

trait Logger {
    public function log($message) {
        echo "[LOG]: $message\n";
    }
}

class Product {
    use Logger;

    public function save() {
        $this->log("Product saved successfully.");
    }
}

class User {
    use Logger;

    public function register() {
        $this->log("User registered.");
    }
}
Enter fullscreen mode Exit fullscreen mode

Here, both Product and User can use the log() method, even though they don’t extend the same parent class.


What if Two Traits Have the Same Method?

You can solve method conflicts using insteadof and as

trait A {
    public function speak() {
        echo "Trait A\n";
    }
}

trait B {
    public function speak() {
        echo "Trait B\n";
    }
}

class Example {
    use A, B {
        B::speak insteadof A;
        A::speak as speakFromA;
    }
}
Enter fullscreen mode Exit fullscreen mode

Now you can control which method is used.


Can Traits Have Properties ?

Yes, they can! But be careful. If two traits define properties with the same name, and you use both in the same class, PHP will throw an error.

trait Configurable {
    protected $mode = 'dev';
}
Enter fullscreen mode Exit fullscreen mode

Best Practices

  • Use traits for generic and reusable features (like logging, caching, validation, etc).

  • Avoid putting complex business logic inside traits — this can make testing and maintenance harder.

  • Use clear names for your traits: HasLogger, CanCache, HandlesValidation, etc.


Laravel Example

In Laravel, Traits are great for shared behavior between models:

trait HasUuid {
    protected static function bootHasUuid()
    {
        static::creating(function ($model) {
            $model->uuid = (string) \Str::uuid();
        });
    }
}

class Order extends Model {
    use HasUuid;
}
Enter fullscreen mode Exit fullscreen mode

Simple, powerful, and reusable.


Conclusion

Traits are a powerful tool for PHP developers. They help you keep your code clean, DRY (Don’t Repeat Yourself), and well organized.

If you don’t use traits yet in your daily work, give them a try. Your code will thank you. 😄

Top comments (1)

Collapse
 
xwero profile image
david duymelinck • Edited

Single inheritance is an OO feature, the languages just implement that feature.

A logger is best added using composition.

I think the Laravel example can become a code smell if most of the models have the HasUuid trait. When you see a trait appear multiple times consider using a parent class.

My main point is, use traits when inheritance makes the code difficult to understand.