© Mikael Olsson 2016

Mikael Olsson, PHP 7 Quick Scripting Reference, 10.1007/978-1-4842-1922-5_16

16. Traits

Mikael Olsson

(1)Hammarland, Finland

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 ...

Get PHP 7 Quick Scripting Reference, Second Edition 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.