PHP Traits: Good or Bad?

Share this article

In early March 2012, the PHP Group announced the release of PHP 5.4. Developer eagerly anticipated the release because of the many new features 5.4 would bring, the most sought after being traits. In the build up to the release, Shameer C wrote a fantastic overview of using traits in PHP, and I highly recommend reading Shameer’s article before this one because I assume you have a basic understanding of traits. Traits have been generally accepted by the PHP development community, mainly because it’s a feature that exists in other programming languages like Java, C++, and Phython. Additionally, the benefits of traits have been widely touted, with developers giving their own two cents on how traits can benefit any project, especially as a replacement for OOP inheritance. But are traits actually that good? Are they a feature which will help raise the level of PHP development, or are they just a fad?

PHP Traits are Bad

On the surface, there is strong support for PHP traits because using them can help reduce code duplication throughout your application. In addition, they can help improve maintainability and the cleanliness of your code. Traits are certainly welcomed, but many leading developers fear they may be used in ways that were never intended. Anthony Ferrara is one such developer, with his fear going so far as to contemplate the possibility of traits becoming the next most abused feature alongside eval and constants. But before Anthony makes his case, he raises a very interesting point: traits are actually a collection of specific mixins, which essentially don’t have state. PHP’s implementation of traits does allow states to be used, and therefore traits in PHP are actually mixins. This simple fact questions the true intent of PHP traits as ultimately they are flying under a false flag. There is no explanation regarding why traits are actually processed as mixins rather than the globally-acknowledged stateless mixins they should be. Anthony continues, citing that traits are very close in functionality to what extends allow us to with regard to coupling classes together. With extends being a well-respected and long-used feature, it is only fair to ask whether traits truly have a place in PHP or are they trying to stand atop the shoulders of existing features in an attempt to look tall? Then there’s also the question of interfaces. Many developers have only a vague idea about what the real difference is between interfaces and traits; their ability to be reused is very similar, and the inheritance depth possible with them is also very similar. Are traits actually something new to PHP, or are they really just an upgrade to interfaces?

PHP Traits are Good

Regardless of the unanswered questions, traits are great for PHP, allowing us to create multiple inheritance scenarios (extends only supports single inheritance). Single inheritance has been used for many years now and comes part and parcel with object orientated programming in PHP, which has restricted advanced programmers from developing complex systems while keeping code clean and to a minimum. In other languages, multiple inheritance could be used to eliminate duplicate code in such situations. But multiple inheritance isn’t possible in PHP. Interfaces are instead offered as a substitute, and an unsuccessful one at that. Interfaces are not intended to be used in this way, rather to act as contracts which force any classes that implement it to deliver its functionality. This can help open up the coupling of classes and methods, but doesn’t offer a true substitute multiple inheritance in PHP. A few developers have attempted to create some creative solutions for multiple inheritance in PHP, but many are bloated, making the overall result redundant and more of an experiment than a practical solution. With traits, multiple inheritance can be implemented naturally using ingenious systems. As Shameer showed in his introduction to traits, you can create multiple traits inside classes. John Squibb uses the multiple traits to create a multiple inheritance environment in his 2011 example. Many programmers think multiple inheritance is evil citing the Diamond Problem
, and claim single inheritance provides less headaches. The fact of the matter with PHP isn’t the practicality of implementing multiple inheritance but rather the symbolism that comes with the possibility of implementing multiple inheritance. This has become ever more important in light of many of the programming public stating their dislike for PHP, evident if you google “don’t use PHP”. With the possibility of multiple inheritance, PHP becomes a more challenging, more expressive, and more acceptable programming language, rather than just the “most common web language”. I find this incredibly comforting when Java, Python, or C++ programmers try to dismiss PHP because of its lack of support of standardized programming methods across languages. Traits are a true indication that PHP is slowly and surely become a language which will embrace more and more standard programming techniques, hopefully winning over many more established programmers and developers.

Conclusion

Traits allow PHP developers to create cleaner, simpler, and more efficient code while also allowing more complex systems to be made and experimented with. They’re not good; they are fantastic! They open up another level of development techniques to OOP programmers using PHP, and I believe they are a sign of things to come in future PHP versions. For more information on the topics mentioned in this article, including a low down on traits themselves, please see the following links: Image via Fotolia

Frequently Asked Questions about PHP Traits

What are PHP Traits and how do they work?

PHP Traits are a mechanism for code reuse in single inheritance languages such as PHP. They are a set of methods that you want to use in another class. Traits reduce the limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes. They are not meant to be instantiated on their own. Instead, they are intended to be used within classes to make methods available that can be used in multiple classes.

How do I use PHP Traits in my code?

To use PHP Traits in your code, you first need to declare them using the trait keyword followed by the trait name. Once declared, you can use them in your classes with the use keyword. Here’s a simple example:

trait Hello {
public function sayHello() {
echo 'Hello ';
}
}

class World {
use Hello;
public function sayWorld() {
echo 'World';
}
}

$obj = new World();
$obj->sayHello(); // Outputs: Hello
$obj->sayWorld(); // Outputs: World

Can I use multiple PHP Traits in a single class?

Yes, you can use multiple traits in a single class. You just need to separate them with a comma. Here’s an example:

class Myclass {
use Trait1, Trait2, Trait3;
}

What is the precedence order when using PHP Traits?

When using PHP Traits, the methods from the current class will always override the trait methods. Similarly, trait methods will override inherited methods.

Can I change the method names in PHP Traits?

Yes, PHP Traits provide the ability to change method names in the class that’s using the trait. This is done using the as keyword.

Are there any limitations or drawbacks to using PHP Traits?

While PHP Traits provide a powerful tool for code reuse, they can also lead to confusion if not used carefully. For example, if two traits have methods with the same name, it can lead to conflicts. Also, traits can’t have properties, which can limit their usefulness.

Can I use PHP Traits with interfaces?

Yes, PHP Traits can be used with interfaces. However, traits cannot implement interfaces on their own. The class that uses the trait is responsible for implementing any interfaces.

How do PHP Traits differ from classes and interfaces?

PHP Traits are similar to classes, but they are intended to group functionality in a fine-grained and consistent way. Unlike classes, traits can’t be instantiated. They are similar to interfaces, but they provide method implementations instead of just method signatures.

Can I use PHP Traits in abstract classes?

Yes, PHP Traits can be used in abstract classes. This can be useful when you want to share methods across multiple abstract classes.

Are PHP Traits considered good or bad practice?

The use of PHP Traits is a matter of debate among developers. Some consider them a powerful tool for code reuse, while others see them as a source of confusion and potential conflicts. It’s important to use them judiciously and understand their limitations.

Callum HopkinsCallum Hopkins
View Author

Callum Hopkins is a designer and front-end developer with over 6 years web experience and has a Bachelors degree in Design for Digital Media. With knowledge in both design and development he is able to influence both sides of the web building process, and has a love for complex coding functions and beautiful design. Callum works as a developer for Deer Digital LTD and runs his own personal blog at callumeuanhopkins.co.uk where he writes thought provoking articles.

Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form