The complete guide to Object Oriented Programming

Written by anastasionico | Published 2018/10/02
Tech Story Tags: programming | php | object-oriented | class | objects

TLDRvia the TL;DR App

Introduction

Learning object-oriented-programming is one if not the most valuable skill a web developer can learn.

For instance, there are places, like London that are so competitive that you must have OOP among your abilities in order to get a job as a PHP Developer.

It is a very big step forward to understand and being able to apply the principles but the amount of reward later in your career is going to be huge.

Not to mention the enhancement of the quality of the code you will write and the time you are going to save by learning all these little trick below.

Stay with me for one of the most important learning journeys of your life.

Differences between procedural and OOP

If you came across this article probably you are interested in learning what is object-oriented-programming also called OOP.

In order to do that we will have to take a step back and understand what are programming paradigms and what are the main difference among them.

Until now, you probably have coded in what’s called procedural programming.

You write your PHP at the beginning of the page,

connecting it with your database of choice and creating variable to use just below in the same page,

or maybe create all your PHP code in a single page and then require or include the script in your main page.

It is fine to work like that,

if you need to build something very small this could actually be a good idea because this paradigm creates less verbose code that in OOP,

but there are several problems with this approach that will show up in the long run.

To begin with,

in this way the possibility to reuse the code is very limited if not impossible.

If you need to use the same block of code you need to rewrite it again somewhere else,

if you need to update a functionality you will eventually need to edit all the blocks, and if you forget a block this will lead to problems and errors that will be really difficult to be spotted later on.

Not to mention this way make the code bumbling, thus, very stressful for the eyes to work with, decreasing your focus and lowering the quality of the project.

Another bad news for the practitioner of procedural programming is employment and job prospect in general,

There are few jobs available for web developers who do not know object-oriented programming,

In all honesty,

depending on where you live there will be no job if you do not know and understand the basic of MVC and how frameworks work as well.

To solve this problem read a series of article I have written about PHP frameworks.

On the other hand,

OOP concepts solve these problems while adding new features that provide a modular structure to your project and make it very easy to maintain the existing code which results in much more flexibility,

just by using objects and classes.

What is an object?

As you might already know in PHP and the vast majority of programming languages every data has is own type,

in PHP the types are the following:

  • NULL
  • Booleans
  • Integers
  • Floating point numbers
  • Strings
  • Arrays
  • Resources
  • Callbacks
  • Objects

In this article, we will focus on the last type of the list: Objects.

According to Wikipedia “An object refers to a particular instance of a class, where the object can be a combination of variables, functions, and data structures.

Clear right?Not really.

Think at an object like a building.

A building has several characteristics (in programming they are called properties) such as windows, doors, rooms, walls and can “perform”, please notice the quote, several actions (named methods) like getting heated when it’s cold, get the door locked when the tenants leave, get stuff fixed when something broke.

in PHP you create an object using the new keyword:

Here is an example:

$myHome

Now the variable $myHome contains all the info included in a building.

Don’t worry if it is not clear yet,

In the following sections, we are going to explore the world of OOP by numerous examples.

These examples will supply you a clear and cozy way to understand the concepts in this paradigm and make you ready to write objects, classes, and relationship by yourself.

Classes in PHP

What is a class?

I have already briefly mentioned what an object is and the concept of objects and class are very similar, which could lead in quite a bit of confusion,

So,

Let’s continue with the building example.

Both class and object symbolize a building, they both have properties and methods.

What are the differences then?

Image a class like a blueprint,

in there, there are listed all the properties the building need to have

the building will have windows, rooms, surely a nice color in the facade, a lock in the front gate, an AC system unit for when is hot, a fireplace for when is cold, etc.

An object instead represents the actual building.

The actual numbers of windows, maybe the color of the frames, the exact number of rooms, the status of the lock (is the gate closed? is it open?) and so on…

The “class” keyword

You have already seen that in order to create an object you need to use the new keyword,

But, new what?

The new element that needs to be created is the instance of the class.

Within the class, you will describe all the characteristics that the building must have such as the number of windows, their color, the number of rooms, etc.

I can also add actions that I need the building to “perform” like close the locker of the gate, open the locker of the gate, add windows, turn on the AC.

In order to create a class, you need to use the PHP keyword class, followed by the open brace,

it is a good practice to add the brace on a new line.

Then you need the add the properties, after then the methods the class requires.

Here is how:

class

{

   // building’s properties

   $numberOfWindows

   $colorOfWindows

   $numberOfRooms

   $lockClosed

   // building’s methods

   /*

    *  The closeLock() method set the lockClosed property to true

    *  This means the lock is closed

    */

   function

   {

      $this->lockClosed = true;

   }

   /*

    *  The openLock() method set the lockClosed property to false

    *  This means the lock is not closed, thus, it is open

    */

   function

   {

      $this->lockClosed = false;

   }

   /*

    *  The addAWindow() method add a window to the house

    */

   function

   {

      return

   }

   /*

    *  The removeaWindow() method remove a window to the house

    */

   function

   {

    return

   }

}

$myHome

Here is it,

My home now has 10 red windows, 4 rooms and it is open to everyone that wants to visit me.

The “new” keyword

The last example finished with the command

$myHome

What this new keyword does is to instantiate a new object from the Building class and set it in the variable called $myHome,

I can now call $myHome’s properties and methods.

$myHome

echo

echo

A new element you see in the snippet above is the arrow**->**

Do not be intimidated by this symbol, it is just a syntax of the PHP language to get the element you want to select.

Think when you use an array

echo

The two square brackets simply allow the developer to retrieve only the sixth element of the $shoppingList array (it is not the fifth because arrays start at 0).

You can also instantiate different buildings and this is one of the biggest pros of using OOP rather than procedural,

You can create different objects that will end up having different properties even though they belong to the same class;

$myHome

$myNeighborHome

echo

echo

Consider that this is just the most simple example, soon you are going to see how can we instantiate the same classes with different characteristics, create relationships among classes, and even invoke methods automatically.

Properties of a class

By now you should have understood that variables within a class are called properties (sometimes also attributes, or fields),

they are defined as you do for normal variables but in a class, you will prefix them with a visibility keyword which you will read soon below.

Inside a class methods and properties need to be accessed using $this->propertyName for non-static and self::propertyName for static ones.

Since properties and methods dwell in two different namespaces you can create a property and a method with the same name and they will not conflict.

class

{

   $wifi

   function

       return

   }

}

Methods and parameters of classes

Methods are just like functions,

I like to think of them as the actions that your class can perform.

We have already seen some example before

…

/*

*  The openLock() method set the lockClosed property to false

*  This means the lock is not closed, thus, it is open

*/

function

{

    $this->lockClosed = false;

}

/*

 *  The addAWindow() method add a window to the house

 */

function

{

   return

}

If for instance, you need to create the car class probably you will have the brake() method and the throttle() method, as well as turnLeft() and turnRight().

To add a method you will need the visibility keyword followed by the name of the method you need to create plus the parenthesis that may or not contain parameters, and eventually, the braces that start and end the method’s block.

Even in this case is a good practice to add the braces on a new line.

$this and self::

In order to figure out what $this and self:: do I must explain what the static keyword means.

By declaring static properties and static methods you will make them accessible without instantiating the class.

I will go over this topic again soon but I just want you to know that it is a very powerful feature of object-oriented programming.

Now,

$this is a pseudo-variable and it is used when you need to refer the variable from within the class,

$this is just a reference to the calling object.

class

{

   // building’s properties

   $numberOfWindows

   function

   {

      return

   }

}

As you can see $this->numberOfWindows refers to the $numberOfWindows variable and its value is getting retrieved from the AddAWindow() method.

self:: basically do the same thing but it works on static properties and methods.

class

{

   // building’s properties

   static

   function

   {

      return

   }

}

Conclusion

As you can imagine there is still a lot of things you need to learn about OOP.

We have only scratched the surface but this little step you took today will lead you very far,

I guarantee it!

I am going to publish the second part of this guide soon so,

Stay tuned,

For more about and programming in general head to anastasionico.uk


Written by anastasionico | anastasionico.uk
Published by HackerNoon on 2018/10/02