Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Traits cannot have constants

Description

Constants int traits were added in PHP 8.2. Until then, they were not allowed: at compile time this error was yield.

Example

<?php

trait T {
    const X = 1;
}

echo T::X;

?>

Alternatives

  • Put the constant in the host class.
  • Put the constant in an interface.
  • Do not use the constant.
  • Move to PHP 8.2 or later.

In more recent PHP versions, this error message is now :ref:cannot-access-trait-constant-%s::%s-directly.