PHP 5 (although most of the ideas in this article also apply to PHP 4) has great support for object oriented programming by providing easy class creation. PHP provides every paradigm other “true” OOP languages implement (Python and JAVA, for example), like inheritance, polymorphism and encapsulation.


The basic idea behind inheritance is that similar objects share common properties. So by creating a “generic” class, we can have a blueprint to build our subsequent classes on. Imagine, if you will, a car’s properties: color, number of wheels, horsepower, number of seats, etc. Having this template we can further specialize our cars by extending this class: creating a racing car that has a “nitro” property, or a truck that has a “trailer” property. The bottom line is: create a more generic class that contains most of the common attributes and you will have much less work defining other objects only slightly different. Instead of rewriting the whole code, you just extend it’s properties, saving a lot of time in the process.


As previously explained, one of the main advantages of using objects is that we don’t need to reveal all of its members (attributes or functions); just the necessary interfaces to work with it. Details not useful to the use of these objects should be hidden from the rest of the objects. This is what is referred to as encapsulation.

Levels of visibility

  • public: means that a class member is visible and usable / modifiable by everyone
  • private: means that a class member is only usable / modifiable by the class itself
  • protected: means that a class member is only usable / modifiable by the class itself and eventual sub-classes


Polymorphism is an OOP characteristic that allows the programmer to assign a different meaning or usage to something in different contexts – specifically, to allow a class member to perform different tasks depending on the context it was used. Imagine you have a Person class and two sub-classes of Person: Japanese and American. Both implement a function named talk(), but with different languages and social context. And while both of them are basically People (as they derive from the class Person), their implementation of the function talk() is very different. So you basically have two objects of the class Person in which the talk() function works differently.