Cheat Sheet on Classes, Traits and Interfaces on PHP/Hack


Haven't coded any PHP/Hack for a while, just recall my memory when I need to use Classes, Traits and Interfaces on PHP/Hack. :)

Classes

  • It is the blueprint of the Object.
  • It has the states.
  • Single inheritance Vs Multiple inheritance, the former one is easy to understand, but the latter one is more power but complex.

Traits

  • It is a group of similar functions
  • It does not have a state.
  • Multiple traits.
  • Trait itself can have the implementation in the source code, it is just like copy & paste practice for code sharing. Of course, trait can have the abstract keyword in the methods to explicitly require the classes to implement those methods, like interface.

Interfaces

  • It is a group of functions that the Objects MUST implement.
  • It does not have a state.
  • Multiple interfaces.
  • Interface itself cannot have the implementation in the source code as compared with the trait.
Note:
  • Abstract in PHP. 
    • Basically, it defines the signature of the classes / methods. The abstract class cannot be initialized. It is being used to force the child classes to implement the methods.
  • Interfaces in PHP.
  • Abstract Class Vs Interface.
  • Traits in PHP.

Comments