Introduction to PHP - Object Oriented Programming Part 1

Guest Posts Paolo Nikko Nuñal

Every good programmer knows that OOP (Object Oriented Programming) is the best approach to any programming problems that you may encounter and in this tutorial, we are going to apply OOP and follow the famous DRY approach (Don't Repeat Yourself).

One of the best benefits of using OOP is that the if something changes in your program you only need to change only one to update all of your code. This is especially true in complex systems.

The first part we are going to discuss about how class works.

What is a class?

A class is like a blueprint for a house or a structure that you are planning to build. In here, you define the shape of the house, what type of walls you are going to use, the relationship between the pieces of the house and just about everything that you need to construct.

Classes form the structure of any data and actions when building objects.

Creating a class in PHP is very simple and you can do this. Lets create a person.

<?php
   class Person
   {

   }
?>


Now we have a blueprint for the person its time to add some properties to a person. Typically a person has a name,age, and gender.

<?php
   class Person
   {
       private $name;
       private $age;
       private $gender;
   }
?>


To create a person, we need to instantiate a new class.

$p1 = new Person;


From that piece of code we have created a new person named $p1. But this is just the tip of the iceberg, as we need to add methods and other actions to create a person. The keyword private or public determines the visibility of the property, we have declared it as private meaning it can only be accessed on the class itself.