New to PHP 5.4: Traits

Posted: November 20, 2010 Comments(2)

New to PHP 5.4: Traits – Simas Toleikis.

Really geeking out at the fact that PHP 5.4 includes traits. If you’re not familiar with traits, they’re a method of inheritance somewhat like extending classes. Simas does a great job of explaining the intimate details of traits in PHP 5.4, so I’ll leave it at my excitement about using something like this soon(ish):

trait Singleton {
    public static function getInstance() { ... }
}

class A {
    use Singleton;
    // ...
}

class B extends ArrayObject {
    use Singleton;
    // ...
}

// Singleton method is now available for both classes
A::getInstance();
B::getInstance();

Sweet.

Get my newsletter

Receive periodic updates right in the mail!
  • This field is for validation purposes and should be left unchanged.

Comments

  1. Yep, it can be really useful, but I’m wondering : what is the priority if a trait contain a method that is already defined by the class or the parent class? What if two traits declaring the same method are used?

    Example:

    trait SingletonT1 {
    public static function getInstance() { … }
    }

    trait SingletonT2 {
    public static function getInstance() { … }
    }

    class SingletonC {
    public static function getInstance() { … }
    }

    class A extends SingletonC {
    use SingletonT1;
    use SingletonT2;
    // …
    }

    Which code of getInstance() will be used in this case ? SingletonT1’s ? SingletonT2’s ? SingletonT1’s ?

    P.S.: I know in this case there is no reason of using SingletonT1 or SingletonT2, but in a more complex case it could occur.

Leave a Reply

Your email address will not be published. Required fields are marked *