In demand


Sunday, September 6, 2015

The Worst of Stackoverflow - When to use PHP Traits

I put this post under the heading of " the worst of stackoverflow" because though the question did not orginate at It does illustrate  what goes wrong when a Q&A only forum or social networking website is used as a tutorial platform.

In the facebook PHP group the question was  asked. Using Facebook to ask this question is a demonstration of how social media websites are not the right venue for learning. As bad as StackExchange  is, it is  still a number of levels above the  use of Facebook, Linkedin and Twitter as learning platforms.

Is there simple way to create array of instances(objects) of one class withing another class? Example:

class Class1 {

constructor method

obj1 = new Class1();
+infinite number of objects = new Class1();

class Class2{
list = array of objects automatically added when new instance of Class1 is created;

My answer to the question was simple and straight forward. To give the asker, Dalibor Komaromi more details than I was willing to provide in Facebook. Obviously Facebook is not the tool for delivering complex information but better suited for guidance to other sources. So I pointed them to a great tutorial in a blog I read last month.

What are PHP Traits? 

Traits is a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies.

The benefit of using Traits is that you reduce code duplication whilst preventing complicated class inheritance that might not make sense within the context of your application.
This allows you to define simple Traits that are clear and concise and then mix in that functionality where appropriate.

The best thing was this event is an example of how a reputation system like the one at stackoverflow can get in the way.  It shows a good use of PHP traits in a scenario I might not have come upon myself. Because although traits are a great tool for PHP it is hard to know when to use them. This is mostly because  PHP developers nowadays write so little of their own code choosing instead to use popular  frameworks.

class Base {
    public function sayHello() {
        echo 'Hello ';

trait SayWorld {
    public function sayHello() {
        echo 'World!';

class MyHelloWorld extends Base {
    use SayWorld;

$o = new MyHelloWorld();

Something like the above probably can't be found in Laravel or Symfony PHP Frameworks.

Today's Links

Post a Comment

Print this!