Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <blockquote> <p><em>An often used metaphor to describe Traits is Traits are interfaces with implementation.</em></p> </blockquote> <p>This is a good way of thinking about it in most circumstances, but there are a number of subtle differences between the two.</p> <p>For a start, the <code>instanceof</code> operator will not work with traits (ie, a trait is not a real object) so you can't us that to see if a class has a certain trait (or to see if two otherwise unrelated classes share a trait). That's what they mean by it being a construct for horizontal code re-use.</p> <p>There <em>are</em> functions now in PHP that will let you get a list of all the traits a class uses, but trait-inheritance means you'll need to do recursive checks to reliably check if a class at some point has a specific trait (there's example code on the PHP doco pages). But yeah, it's certainly not as simple and clean as instanceof is, and IMHO it's a feature that would make PHP better.</p> <p>Also, abstract classes are still classes, so they don't solve multiple-inheritance related code re-use problems. Remember you can only extend one class (real or abstract) but implement multiple interfaces.</p> <p>I've found traits and interfaces are really good to use hand in hand to create pseudo multiple inheritance. Eg:</p> <pre><code>class SlidingDoor extends Door implements IKeyed { use KeyedTrait; [...] // Generally not a lot else goes here since it's all in the trait } </code></pre> <p>Doing this means you can use instanceof to determine if the particular Door object is Keyed or not, you know you'll get a consistent set of methods etc, and all the code is in one place across all the classes that use the KeyedTrait.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload