oop-php

Object-Oriented Programming in PHP for Beginners

By Rasyue | On June 14, 2020

For many new coders, beginners or even those who can considered themselves as intermediates, the concept of object-oriented programming can be frightening. In this tutorial, we are going to try to explain the concept of OOP so the beginners in PHP can pick this up and start to use it in their coding.

Procedural Programming in PHP

Before we explain about object-oriented programming, let’s talk about procedural programming for a bit. For those who never heard of this before, procedural is like a programming concept that you used when you first pick up PHP. For example,

<?php

$declare_variable1 = 'my variable value in string';
$declare_variable2 = 123 //integer
$declare_variable3 = true //boolean

//declaring function
function myPHP(){
   echo 'Rasyue Blog';
}

//calling your function
myPHP();

//you can also pass argument to your function
function nextPHP($input){
  echo $input;
}
nextPHP('Rasyue Blog Here too');

?>

With procedural programming, if you are writing a PHP script, you will group a chunks of your code that is trying to achieve a single purpose into a function and name the function with related name. For example:

<?php

/* a chunks of code to connect to database that you group into a function 
and name the function accordingly
*/

function connect_db(){
    global $sql_host, $sql_username, $sql_password, $sql_database;
    $conn=new mysqli($sql_host,$sql_username,$sql_password);

    if(mysqli_connect_error($conn) !== null) {
        return false;
    }

    $conn -> select_db($sql_database);
    return $conn;
}

?>

Now, let’s try to write the same function to achieve the same purpose but in OOP style!

Object-Oriented Programming (OOP)

When we talk about OOP, we can never run away from the terms like:

  • Class
  • Object
  • Methods
  • Properties
  • Constructor

I will try to explain the terms above as simple as possible so you will be able to understand it. Let’s start with Class.

So what is Class ?

Class – A class is like a blueprint or a template that you create to achieve a purpose. In this blueprint or template you can define methods or properties that you need to achieve the functionality that you want.

Object – An object is essentially an instance of a Class. Basically, it’s like declaring a variable with a string value or maybe an integer or a boolean value. Declaring an Object meaning you will have all the properties or methods of the Class.

Methods – Methods are basically functions. Like how you write a function in procedural programming, in Class, you can also write functions to achieve something be it connecting to a database, fetching data from a database or maybe writing a function to consume a REST API. Everything is up to you.

Properties – Properties are more or less like attributes. For example, when you are writing a Class, you might want that class to have a value of something, for example you want a Class to have a base URL value of www.rasyue.com/ or maybe you want a Class to have properties of height, weight, length or width.

Constructor – Now calm down and take a breather first. Just think of constructor as a function that is automatically run whenever your create an Object of that Class. Simple thing.

Access Modifiers – This is a thing that allows you to set access to properties or methods in the Class. There are three access modifiers you can use public, private or protected. We will talk more about this in our example below

More on OOP in PHP

Let’s try to write a Class and then create an Object which is an instance of the Class that we created.

<?php

//declare our class here
class Rasyue{
  
}

/* and that's it! 
   this is how we define a class however the class Rasyue does not have
   any methods, properties or even a constructor, lets declare another Class below
*/


class RasyueOne {
// lets declare properties here

// this is like declaring a variable but in a Class, we call this properties because we are giving attributes to the Class
public $property_one;

// this is a property that holds the string value
public $property_two = 'Property Number Two';

}

/* Let's create an instance of the Class or as we call it, Object and try
 to access the $property_two value
*/

$rasyue = new RasyueOne();

/* this is how we create an instance of a Class, $rasyue is now an object
   and with that $rasyue now holds all the properties or methods of the Class RasyueOne(), let's try to access the properties of RasyueOne
*/

echo $rasyue->property_two

/*
if we do this, it will return an error. if you are wondering why, it is because, although we have to access to the properties of the Class, we need a method to be able to access it

Let's remove all of this and continue below.
*/

?>

Remember to remove the above and start with below PHP code.

class RasyueOne{
//declare properties here

public $property_one;
public $property_two = 'Property Number Two';

/* now in order for our object to echo out or access this properties, we need a method, let's define a method
*/

 function getProperty(){
   return $this->property_two;
 }

}

/* 
Now let's create an Object of this Class and call the method
*/

$rasyue = new RasyueOne();

echo $rasyue->getProperty();

Now, if you copy and paste the above, it should return the value of $property_two. Now, let’s talk a bit about the class that we defined. First, we define a class name RasyueOne. Then we declare two properties, the first property is empty while the second property has a string value. Both of these properties have an access modifier that comes before their variable which in this case is public. Now, access modifier is essential when you are defining Classes, the access modifier public tells PHP that these properties can be access from anywhere hence why it’s public. There are two others which are protected and private.

The next part is that we defined a method or if you rather like to call it function. It is basically a function but because we define it in a Class, we will refer to it as methods. The method getProperty() returns the value of $property_two. Nothing to complicated about the method.

The last part is, we declare a variable $rasyue = new RasyueOne().
This is how we create an Object, we first write a variable followed by the key new and the name of the Class, in this case the Class name is RasyueOne(). Now the variable $rasyue is an Object and with that $rasyue will be able to access all the properties or methods of the Class.

Wait! Hold on!
What about $this->property_two? What is this $this you may ask ? Well, do not be afraid of this $this, we are going to talk about this in a second, For the time being, just treat $this like a special variable that you use to access the Class methods and properties.

What is constructor in a Class?

Now, let’s talk a bit about constructor. What is a constructor?
Constructor is a special function that we declare in a Class with the name __construct(). So, what’s so special about constructor?

Well a constructor is a function that will always get call automatically every time you create an instance of a Class. Let’s write some code to help you better understand constructor. Copy and paste the below code in a new php file to make things easier.

<?php

class Rasyue{

public $name;
public $age;
public $weight;

  function __construct($name, $age, $weight){
     $this->name = $name;
     $this->age= $name;
     $this->weight= $name;
  }
  function returnProperty(){
     $text=  'My name is '.$this->name.'. My age is '.$this->age.'. My weight is '.$this->weight;
     return $text;
  }
}


$rasyue = new Rasyue('Rasyue', '100', '1080kg');
echo $rasyue->returnProperty();

?>

With the above code, you will get a line echo out that spells My name is Rasyue. My age is Rasyue. My weight is Rasyue .

Ok ok! Hold up! Hold up! Back up a bit!

Why does the Object that we declare as an instance of the Class Rasyue now accepts argument, not to mention 3 arguments now.
What about the part $this->name or $this->age or $this->weight ?
Is $this->name different than $name ?

Ok, let me explain!

The new thing that we defined in class Rasyue is a constructor. In procedural programming, when we define a function, we can write the function to accepts arguments and in turn use that arguments/inputs as part of the code in the function. So how do we allow Classes to accept argument as well ?
Simple, we just have to declare like so $rasyue = new Rasyue('args1', 'args2'). However doing so will be a waste as we won’t be able to accept or handle the inputs/arguments because the Class won’t have a method to handle it.
That is why we define the constructor, of course a constructor purpose is not limited to this, but this is the best example to show you the purpose of defining a constructor.

The constructor that we define in Rasyue will in turn set the 3 properties of the class to the value of the 3 inputs that we pass in during the instantiation of the class. Take a look at the code below.

class Rasyue{

/* these are the 3 properties that we declare which belongs 
   to this class Rasyue
   but wait, let's take a look at the __construct method, it accepts 3 arguments which have the same name as the properties, so how do we make sure that we don't get this mixed up ? Simple, by using $this followed by the name of the methods or properties, we can access the properties or methods that belong to the Class. Also this is the only way for us to access properties, using $this->name or $this->age.
Note that we omit the $ or the dollar sign from the properties.
If you want to call the methods inside a class you may also do it like so $this->methodname

Let's continue in the __construct()
*/
public $name;
public $age;
public $weight;

  function __construct($name, $age, $weight){
/*
now, there are 3 inputs called $name, $age, $weight, of course you can set the variables name anything you like, but I did it this way to show you the difference between properties and variables.

*/
     // with this we set the property name to the input $name
     $this->name = $name;
     $this->age= $name;
     $this->weight= $name;
  }
  function returnProperty(){
     $text=  'My name is '.$this->name.'. My age is '.$this->age.'. My weight is '.$this->weight;
     return $text;
  }
}

There you have it folks! As a practice, try to write a Class that can make an API call. See you in the next post!

Leave a Reply

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

*

*
*