Skip to content

MIR0720

TraitInstantiation

A trait is used with new. A trait only supplies members to the classes that use it; PHP throws Cannot instantiate trait for new Loggable(). Inside a trait, new self() and new static() name the using class and are fine.

<?php
trait Loggable {
public function log(string $message): void {}
}
$logger = new Loggable(); // cannot instantiate trait

Instantiate a class that uses the trait:

<?php
final class Logger {
use Loggable;
}
$logger = new Logger();