What are traits, and how are they used? Michael Stowe explains

An Introduction to Traits
Keine Kommentare

Traits are the arguably the headline feature of PHP 5.4, and they’ve stirred up a lot of interest among developers – like previous updates to the language, they have the potential to make everyone’s lives easier. If you’re not quite up to speed yet, here’s what you need to know.

What are traits?

One of the latest additions to the PHP programming language is traits, or the ability to implement horizontal design within your classes. Prior to PHP 5.4 (released March 1, 2012) we could utilise popular object-oriented concepts such as classes, abstracts, and interfaces, and even extend them vertically, allowing one class to utilise the properties and methods of its parent class, and the classes above that. However, we were still limited in code reusability – eventually we would code ourselves into a corner, becoming limited by the original intent of the parent class (or one of its many extensions).

Traits, on the other hand, allow you to “include” outside collections on demand, providing the ability to extend your class horizontally. Imagine the ability to pull in multiple “classes” without requiring them to be extended upon one another. Instead of now being restricted by this vertical chain of design, we can utilise traits as needed to create the class we want based off existing code bases.

In other words, a trait is really nothing more than a set of methods that get pulled into the calling class. While it is its own separate collection, once called in, the trait methods act as if they are part of the class, allowing direct access to the methods through the use of $this and self.

Unlike many programming languages, PHP allows you set up properties in your trait, giving you the ability to predefine how these properties should be set up. This provides tremendous flexibility in setting up a trait for horizontal reusability. However, this powerful feature comes with a small caveat – if the class declares the property again PHP will throw an E_Strict warning, or, in the case where the properties are not identical in type, value, and visibility, a fatal error.

Also, be aware that PHP 5.4 has added some reserved keywords, meaning you cannot use “trait”, “insteadof”, or “callable” as function or method names.


Unsere Redaktion empfiehlt:

Relevante Beiträge

Benachrichtige mich bei
Inline Feedbacks
View all comments
- Gib Deinen Standort ein -
- or -