Object-Oriented Programming In PHP – Part I

Welcome to Object Oriented Programming in PHP. According to Wikipedia , Object-oriented programming(OOP) is a programming paradigm that represents concepts as objects that have data fields (attributes that describe the object) and associated procedures known as methods. An object  is an instance of a class – that is, you use a class to create an object. The easiest way to understand OOP is using a real-world example.


Looking at the above image makes our work really easier here. In real life, there is something called a car. But you can’t just walk to your friend’s house and say I own a car and assume that they will automatically know what type of car you have. So, in other words, our car is a class and from that car class, we can create different kinds of cars(objects) like Toyota, Ford, Chevy etc. Oh, don’t forget the VW Bug!

To make this a little understandable, we can break the car concept into data fields and methods. Every car has some color(attribute), and most importantly they move(method). What else can you think of? A car can either be on or off. The other fact is that different cars have different other properties. Think of them!

Another good example is a cookie-cutter. You can think of a cookie-cutter as a class and the cookies themselves as objects. Using your cookie-cutter, you can create all shapes of cookies, using different recipes.


One of the biggest advantage of OOP is its capability to support and encourage encapsulation – also known as data hiding. Essentially, access to the data within an object is available only via the object’s operations, known as the interface of the object.


Polymorphism means different classes can have different behaviors for the same operation. Consider having a class Car and a class Bicycle. They can both have different move operations. Polymorphism is more a characteristics of behaviors than it is of objects. In PHP, only member functions of a class can be polymorphic.


Inheritance allows you to create a hierarchical relationship between classes using sub-classes. If you are asking whether this works like a son inheriting a million dollars from his father or not, then you are thinking right! A subclass inherits attributes and operations from the superclass.  An example could work like this: we both know that a car and a bicycle have certain things in common. You could then use a class called vehicle that contain a color attribute and a move operation that all vehicles have. You can simply then have both car and bicycle classes inherit from vehicle class – how nice right?

Using inheritance might save you work if operations can be written once in a superclass rather than many times in separate subclasses. It might also allow you to more accurately model real-world relationships. If a sentence about two classes makes sense with  “has-a” between the classes, inheritance is probably appropriate. The sentence ” a car is a vehicle” makes sense, but the sentence “vehicle is a car” does not make sense because not all vehicles are cars.Therefore, car can inherit from vehicle.

Creating Classes, Attributes and Operations

Let us get our hands dirty here by …you guessed it, creating classes, attributes and operations in php. When creating a class, the keyword class must be used.

Object Oriented Programming in PHP – Code Examples


< ?php #the structure of a class #opening and closing braces #---------------------------------------------------------# class classname{ #some cool things here please #do stuff here - attributes and operations } #---------------------------------------------------------# #Obviously, without attributes and operations, our class #is not that useful. So let us add some attributes #---------------------------------------------------------# class classname{ public $attribute1; public $attribute2; } #---------------------------------------------------------# #the above code creates a class called classname and #two attributes $attribute1, $attribute2 with [public] #visibility. visibility options[public, private, protected] #We have added attributes but we have no way of operating #on them, so why not add some methods to our brand new class? #---------------------------------------------------------# class classname{ public $attribute1; public $attribute2; #now add two methods here function operation1(){ //do some cool math here } function operation2($param1, $param2){ //do some other crazy rocket-propulsion. } } #--------------------------------------------------------# #As you can see, we created two functions inside our class #and we call such functions ... methods because they are in #the class! ?>


Most classes have a special type of operation called a constructor. A constructor is called when an object is created and also normally performs useful initialization tasks such as setting attributes to sensible starting values or creating other objects needed by the object.

A constructor is declared the same way as other operations inside a class but has the special name __construct() and although you can manually call a constructor, its purpose is to be called automatically when an object is created. Time for an example:

< ?php #declaring a constructor for a class #----------------------------------------------# class classname{ public __construct($param){ //do some initialization or setup here echo "Constructor called with parameter: ".$param."

#PHP supports function overloading – providing more than one
#function with the same name with different numbers or types
#of parameters!


Just like constructors, there exist destructors. They are special in the sense that they don’t take any parameters and declared as __destruct(). When all references to a class have been unset or fallen off a scope, it gets destroyed. If you then want to have some functionality executed before the class is destroyed, you use the destructor!

Instantiating a Class

After declaring your class, you need to create an object – a particular individual that is a member of the class. You can then do something with it. As I mentioned earlier, it is called instantiating or creating an instance of a class. You create an object by using the new keyword. When you do so, you need to specify which class your object will be an instance of and provide any parameters required by the constructor. Time for an example:

< ?php #from our first class earlier; class classname{ public __construct($param){ echo "Constructor called with parameter: ".$param."

#——————–NOW INSTANTIATE————————-#

$a = new classname(“first”); #param – first
$b = new classname(“second”); #param – second
$c = new classname(); #param – none

#Running the above code will result in: guessed it?
#Constructor called with parameter: first
#Constructor called with parameter: second
#Constructor called with parameter:

Using Class Attributes

Within a class, you have access to special pointer called $this. If an attribute of your current class is called  $attribute you refer to it as $this->attribute when either setting or accessing the variable from an operation within the class.

< ?php #demonstrating how to use attributes inside a class class classname{ public $attribute; function operation($param){ $this->attribute = $param; echo $this->attribute; } } #Access modifiers [public, private, protected] determine #whether you can access an attribute outside a class or not. #---------------------CONSIDER THIS--------------------# class classname{ public $attribute; } $a = new classname(); $a->attribute = “value”;
echo $a->attribute;


#Since the $attribute variable is declared as [public],
#we can access it outside and even change the value!

Doing what we did above(accessing attributes and changing their values outside a class is obviously not a good idea.To avoid such a problem, we take advantage of OOP’s encapsulation. We enforce it by using __get and __set functions. These functions are commonly known as setters and getters or accessor functions. Example:

< ?php class classname{ public $attribute; function __get($name){ return $this->$name; } function __set($name, $value){ $this->$name = $value; } } ?>

Now our above code provides minimal functions to access our attributes. Basically, our __get function returns the value of the attribute with the same name as the one passed in ($name). __set() on the other hand takes a name of an attribute and a value, then sets the value of the attribute to the value passed in!

One thing to remember is that you do not call __get and __set functions directly. You may be asking, so how do we then call them? Here is the thing: when you instantiate an object like this:


< ?php $a = new classname(); ?>

You can then use __get() and __set() functions to check and set the value of any attributes: If you type:

< ?php $a->$attribute = 5;


The above statement implicitly calls __set() with the value of $name set to “attribute”  and the value of $value set to 5. You need to write __set() to do error handling.

The __get() function works in a similar way. If, in your code, you reference

< ?php $a-> attribute;

this expression implicitly calls the __get() function with the parameter $name set to attribute. It is up to you to write the __get() function to return the value.

Let us improve our __set() function to do some error checking!

< ?php function __set($name, $value){ if(($name == "attribute") && ($value >=0) && ($value < =100)){ $this->attribute = $value;


Access Modifiers Debunked

There are three main access modifiers and they are described below:

  1. public – this is the default option. That means that failure to declare an access modifier on an item makes it public. The particular item will be accessible both in and outside the class.
  2. private – this means that the marked item is only accessible within the class. You may also declare some methods as private – for example if they are utility functions used only inside the class. Items that are private will not be inherited.
  3. protected – this means the marked item can only be accessed within the class. It also exists in subclasses! Think of this as halfway between private and public.

Calling Class Operations

Let us quickly look at an example of calling operations(methods)!

< ?php class classname{ function operation1(){ //---do something } function operation2($param1, $param2){ //---do other stuff } } #create an instance now $a = new classname(); #You then call the operations as you would call any #other function: $a-> operation1();
$a-> operation2(12, ‘test’);

#if our operation returns something, you can store it as:
$x = $a-> operation1();
$y = $a->operation2(10, “sample”);


Implementing Inheritance In PHP

If a class is to subclass another class, you can use the extends keyword. Example here: Consider a class B that extends another class previously created by a friend A.

< ?php class B extends A{ public $attribute2; function operation2(){ //do something here } } class A{ public $attribute1; function operation1(){ //do something here } } #Now you can do these: $b = new B(); $b-> operation1();
$b-> attribute1 = 10;
$b-> operation2();
$b-> attribute2 = 5;

#Since class B extends class A, you can access both
#operation1() and $attribute1
#NOTE: inheritance works only in one direction – that is:
#a subclass can only inherit from the superclass and not
#the other way round.
#———–CONSIDER THIS NOW——————–#

$a = new A();
$a-> operation1(); #valid
$a-> attribute1 = 21; #valid
$a-> operation2(); #invalid
$a-> attribute2 = 100; #invalid

I am going to stop here then continue tomorrow. I hope you found this helpful. If you have any questions or errors you might have spotted, let me know. There are just a few more concepts that should fit into a single post bringing this OOP topic to an end. Stay safe and hope to see you soon! Please drop me a line in the comment section.

Written By Elisha Chirchir

Elisha Chirchir is a software developer. He is also the founder of Simple Developer and co-founder of Instinctive Software Solutions. On any given day, he works on both Android and Web Development. During his 'free time', he offers training to those interested in learning how to code in php, java, python, javaScript etc. You can easily find him on StackOverflow Android chatroom or on Twitter @Eenvincible

One Comment on “Object-Oriented Programming In PHP – Part I

  1. […] I created a post on OOP and had to split it in two to avoid making it too long. Today, I am going to finish up the […]

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.