Skip to content
Tutorials Center
My learning

Topics

Lesson 51 of 147 ยท Object-Oriented PHP

Traits

Share methods between unrelated PHP classes with traits: use, precedence, insteadof and as, abstract and static members, trait constants and when to avoid them.

Inheritance shares code down a family tree, but a PHP class can have only one parent. What if an Invoice, a User and a BlogPost all need the same "created at / updated at" timestamp methods? They aren't related, and forcing them under a common Model parent just for two methods would tangle the design. Interfaces don't help either: they declare methods but contain no code.

A trait fills this gap. It's a bundle of methods (and properties) that you copy into any class with a use statement. Think of it as compiler-assisted copy and paste: the trait's members behave exactly as if you had written them inside the class. Traits are used heavily in frameworks; Laravel models, for example, gain soft deletes and notifications by using traits.

This lesson covers declaring and using traits, the precedence rules, resolving name conflicts with insteadof and as, abstract and static members, trait constants (PHP 8.2), and, just as important, when a trait is the wrong choice.

Declaring and using a trait

Declare a trait with the trait keyword, then pull it into a class with use inside the class body. (This use has nothing to do with the use that imports namespaces, or the use of closures; the keyword is shared.)

PHP One trait, two unrelated classes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Both classes now have touch(), timestamps() and the two private properties, without sharing a parent. Inside trait methods, $this is the object of whichever class uses the trait, and private trait properties become private properties of that class.

Notice the last line: instanceof HasTimestamps is false. A trait is not a type. You can't type a parameter as HasTimestamps, and class_uses() is the only way to ask whether a class uses one. When you need a type, pair the trait with an interface (shown later in this lesson).

A class can use several traits at once, either in one statement (use HasTimestamps, SoftDeletes;) or in several. Traits can also use other traits.

Precedence: class, trait, parent

When a method with the same name exists in more than one place, PHP picks it in this order:

  1. A method declared in the class itself wins.
  2. Otherwise, the trait's method is used.
  3. Otherwise, the method inherited from the parent class.

So a trait overrides inherited methods, and the class overrides the trait:

PHP Which method wins?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output also shows two details. parent::hello() inside the trait reaches Base, because the trait's code runs as part of Child. And self::class inside the trait is Child, not Friendly: self, static and __CLASS__ all refer to the class using the trait. (The magic constant __TRAIT__ gives the trait's own name.)

Resolving conflicts: insteadof and as

If two traits used by the same class both define a method with the same name, PHP can't guess which you want and stops with a fatal error, unless you resolve it. Write a block after use with:

  • A::method insteadof B; to choose trait A's version over trait B's.
  • B::method as otherName; to keep the other version under an alias.
PHP Two traits with the same method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Without the insteadof line, this class would fail to compile with "Trait method CsvExport::export has not been applied as Report::export, because of collision with JsonExport::export". Note that as alone doesn't resolve a conflict: it adds an extra name, but both traits would still try to provide export().

Changing visibility with as

as can also change a trait method's visibility in the using class, with or without a new name:

PHP
class Report
{
    use CsvExport {
        export as protected;                 // export() becomes protected
        export as public toCsv;              // ...and also public under a new name
    }
}

This is handy when a trait offers a method you want to use internally but not expose, or the reverse.

Abstract methods: what a trait needs from its class

The traits above called $this->data(), assuming the class has it. That's fragile: a class that forgot data() would fail only at runtime. A trait can state its requirements with abstract methods, and PHP then checks at compile time that every using class provides them:

PHP A trait that requires a method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

This also shows the most useful pattern for traits: an interface plus a trait that implements it. The interface Greeter is the type that functions accept; the trait Greets is a ready-made implementation classes can use, so they don't each rewrite greet(). Since PHP 8.0, abstract trait methods are checked against the implementation's signature, and they may even be private.

Static members and constants in traits

Traits may contain static methods and static properties. Each class that uses the trait gets its own copy of a static property, which is exactly what you want for things like per-class counters:

PHP Static properties are per class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Order and Customer each count their own instances, because the static property is copied into each class. Static members in general, including why shared static state can be risky, are the subject of Static Properties and Methods.

Since PHP 8.2, traits can also declare constants. As with static members, you reach them through the class that uses the trait, never through the trait itself:

PHP
trait Retries
{
    public const int MAX_ATTEMPTS = 3;          // typed constant: PHP 8.3

    public function attempts(): string
    {
        return 'up to ' . self::MAX_ATTEMPTS . ' attempts';
    }
}

class Mailer
{
    use Retries;
}

echo Mailer::MAX_ATTEMPTS;      // 3
echo Retries::MAX_ATTEMPTS;     // Error: Cannot access trait constant Retries::MAX_ATTEMPTS directly

Calling a static trait method directly (CountsInstances::created()) still works but has been deprecated since PHP 8.1; always call it on a class.

Properties in traits

A trait property must not clash with a property of the class. If both declare the same property, they must be fully compatible (same visibility, type, readonly modifier and default), otherwise compilation fails. In practice, keep trait properties private, name them specifically, and let the trait own them.

When not to use traits

Traits are convenient, and that's the danger. Because they insert code silently, overusing them produces classes whose behavior is spread over many files. Ask these questions before writing one:

  • Is this really shared behavior, or a hidden dependency? A trait that needs a database connection, a logger and three abstract methods is a class pretending to be a trait. Make it a real class and pass it in through the constructor (composition). For example, instead of use SendsEmails;, give the class a Mailer $mailer property.
  • Do callers need a type? Traits aren't types. If code will check "can this object do X?", define an interface; a trait can supply its implementation.
  • Will you test it alone? You can't instantiate a trait, so testing one means creating a dummy class. A separate class is easier to test.
  • Is it small and self-contained? Good traits are short, focused and depend on nothing except the class's own state: timestamps, simple counters, a toArray() built from properties, an interface's boilerplate.
Good use Better as something else
Default implementation of a small interface A service with dependencies (use a class + constructor injection)
A few helper methods many unrelated classes need "Base class" code for one family (use an abstract class)
Framework conventions (timestamps, soft deletes) Reusing logic just to avoid writing a class

OOP Design Principles explores composition over inheritance, which applies to traits too.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A class extends Base and uses trait T. Base, T and the class itself all define hello(). Which version runs on $obj->hello()?

    Precedence is class first, then trait, then parent. The trait would win only if the class didn't define hello().
  2. 2. Two traits A and B both define run(). What does use A, B { A::run insteadof B; B::run as runB; } give the class?

    insteadof chooses A's run() for the name run, and as adds B's version under the alias runB.
  3. 3. Class Post uses trait Sluggable. What does var_dump($post instanceof Sluggable); print?

    Traits are not types. Use class_uses() to check for a trait, or pair the trait with an interface for type checks.
  4. 4. Classes Order and Customer both use a trait with private static int $created = 0; and increment it in their constructors. After creating 2 orders and 1 customer, what is Order::created()?

    Each using class gets its own copy of a trait's static property, so Order counts only its own 2 instances.
  5. 5. Which of these is the best fit for a trait?

    Traits work best when small and self-contained. Code with dependencies belongs in a class you inject; family logic belongs in an abstract class.

Summary

  • A trait is a reusable bundle of methods and properties. use TraitName; inside a class copies its members into that class.
  • Inside a trait, $this, self, static and __CLASS__ refer to the using class; __TRAIT__ is the trait's name.
  • Precedence: the class's own method beats the trait's, and the trait's beats the inherited one.
  • Same-named methods from two traits must be resolved with insteadof; as adds an alias or changes visibility.
  • Abstract methods let a trait require methods from its class. Pair a trait with an interface when callers need a type, since traits aren't types (instanceof is false; use class_uses()).
  • Each using class gets its own copy of a trait's static properties. Trait constants (PHP 8.2) are accessed through the class, never the trait.
  • Keep traits small and self-contained; use composition (inject a class) for anything with dependencies.

Next: Static Properties and Methods