CHAPTER 16

image

Traits

A trait is a group of methods that can be inserted into classes. They were added in PHP 5.4 to enable greater code reuse without the added complexity that comes from allowing multiple-inheritance. Traits are defined with the trait keyword followed by a name and a code block. The naming convention is the same as for classes, with each word initially capitalized. The code block may only contain static and instance methods.

trait PrintFunctionality{  public function myPrint() { echo 'Hello'; }}

Classes that need the functionality that a trait provides can include it with the use keyword followed by the trait’s name. The trait’s ...

Get PHP Quick Scripting Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.