object-orientation programming-concepts

What is object orientation?

Written on 18th Jan 2019
It will take between 5 and 6 minutes to read this article

What is object orientation? Object orientation, sometimes known as OOP (object oriented programming) can often seem daunting when you first learn about it. You'll soon become used to Object Oriented Programming and it will revolutionise the way you think about code.

Up until now you've probably been writing your code procedurally. That is to say that you have all your code in one file which executes top to bottom without really leaving that file. Let's look at a real life example;

So currently, we might want to display something based on whether it's morning, afternoon or evening. Procedurally we probably would do something like;

<?php
 
// We get the hour
$hour = date("H");
 
if ($hour < "12") {
// if the hour is less than 12 (noon)
echo "Good morning";
} else if ($hour >= "12" && $hour < "17") {
// otherwise if it's greater than or equal to 12
// but less than 17
echo "Good afternoon";
} else if ($hour >= "17" && $hour < "19") {
// otherwise if it's greater than or equal to 5pm
// and less than 7pm
echo "Good evening";
} else {
// otherwise we can assume it's past 7pm
echo "Good night";
}

But it's not quite as readable as when we abstract out the time of day functionality and put it into a reusable class. This now becomes Object Oriented programming rather than transactional.

<?php
 
// Instantiate the new time class
$time = new MyTimeClass();
 
if ($time->isMorning()) {
echo "Good morning";
} else if ($time->isAfternoon()) {
echo "Good afternoon";
} else if ($time->isEvening()) {
echo "Good evening";
} else {
echo "Good night";
}

However, we're slightly jumping ahead of ourselves! We need to talk about encapsulation first!

The four principles of object-oriented programming are encapsulation, abstraction, inheritance, and polymorphism.

Encapsulation

Encapsulation is where the state of the class (object) you are creating is not available outside of that object. Confused? I'm not surprised! Let's take a look in context of our MyTimeClass class.

This is the functionality we took out of the procedural code and created an object to deal with this logic;

<?php
 
class MyTimeClass
{
private $morningStart = 0;
private $morningEnd = 12;
private $afternoonEnd = 17;
private $eveningEnd = 19;
 
/**
* Checks if it is morning
*
* @return bool
*/
public function isMorning(): bool
{
return date('H') < $this->morningEnd;
}
}

So as you will notice there are a few items, known as properties, which are protected. This means you can not access these from outside of the class. Only the class itself can alter these properties. This protects the class from unexpected change, and you define how you want to allow other objects to interact with your object, if indeed you want them to be able to.

So earlier on, we made code more readable and more reuseable by instantiating a new class (object) and asked the class if it was morning for example $time->isMorning();

Abstraction

Abstraction is taking out a core piece of functionality and only exposing a high-level mechanism for using it. Let's again take our MyTimeClass object as the example. When we ask our MyTimeClass if it's morning, we don't really care how it comes to it's answer of yes or no, we just want the result. In the same way you might get into a taxi, you don't care which route it takes as long as it gets you to the destination. Abstraction is about taking the detail of a function off the radar and just providing you the over all.

Inheritance

Inheritance works a little in the way it does in the real world. Let's take out MyTimeClass object again. From our class, we can determine whether it's morning, afternoon, evening or night-time. However, we can inherit, or extend, from another class (called a parent class), which simply put we can inherit most if not all of it's methods (functions) and properties (variables). Let's inherit from our MonthsClass.

<?php
 
class MyTimeClass extends MyMonthClass
{
protected $morningStart = 0;
// ...
<?php
 
class MyMonthClass
{
/**
* Is January
*
* @return bool
*/
public function isJanuary(): bool
{
return date('M') == 'January';
}
}

This way, when we instantiate MyTimeClass, we can now utilise any public or protected methods and properties. So in theory we could say if it's $time->isMorning() && $time->isJanuary() then we could display something only supposed to be seen during mornings in January.

Like wise we could extend the the MyTimeClass to a child class and create a new function off it which would bring all of the months and times of day functions but we could create another function in the child class which tells us if it is January and Morning: isJanuaryAndMorning()

Polymorphism

Polymorphism comes from two greek words meaning many forms. One fof my favourite analogies to help you understand what polymorphism is the form of a button. With a button, there is generally only one action; you press it (or if you're a child you press it multiple times without a care in the world). What the button does on press depends on what it has been hooked up to.

One way to make use of polymorphism is to use Interfaces. Interfaces are like a template of functions a class should contain. We know that a button should have a press function. Let's create that interface;

<?php
 
interface Button
{
public function press();
}

Now, when we make a class and implement the above rules (which is known as a contract) we must have a press function otherwise a fatal error will occur.

<?php
 
class ChocolateButton implements Button
{
public function press()
{
return dispense_chocolate();
}
}

Now we can instantiate the ChocolateButton class and execute the press function and we know it will be there. Now we've got our template (contract) set up, we can make other buttons which also have the press function on them.

<?php
 
class CrispsButton implements Button
{
public function press()
{
return dispense_crisps();
}
}

As you'll see below it's now easy to swap in and out implementations of the same core template

<?php
 
class Handler
{
public function handle($event)
{
if ($event == 'chocolate') {
return (new ChocolateButton)->press();
}
 
if ($event == 'crisps') {
return (new CrispsButton)->press();
}
}
}
Code highlighting provided by torchlight.dev.