oop php

An Absolute Super Beginner Guide to Object Oriented Programming (OOP) in PHP

What the hell is Object Oriented Programming (OOP)?

OOP is a programming model based on the concept of something called objects.

Objects?

An object is a self-contained component which consists of methods and properties. Now, what does that mean?

Let’s draw an example of a real life object. Let’s say a book.

A book has following methods (i.e actions you can do with it):

  • Open
  • Read
  • Close etc.

And, it has the following properties ( the characteristics that our book object has):

  • no of pages
  • color
  • writer etc.

Objects don’t even need to be real-life objects. Let’s say you have a form where a user comments. So, you’ll need 3 objects to model this.

  • form object
  • user object
  • comment object

You can think of a single object as a unit of code which comparable to single atom in science terms.

Now sometimes you may come across the definition down below.


Object is an instance of class.

What does the above definition mean?

What is a class?

Class is a blueprint of an object.

It is a template from which objects are created.

It is just a logical representation and is not stored in any memory. Objects, however, are stored in memory.

So, think of a class as a model, blueprint, map or a factory through which we create objects.

Now, we talked about two things while talking about objects. Let’s look at them briefly.

  1. Methods: If simply explained, a function that exists inside a class is called a method. Action things.
  2. Properties: Properties are class member variables. They are also referred to as “attributes” or “fields. They are defined using private, public and protected access modifiers.

A shopping cart object may have properties such as number of items, name of items, individual price of items and a method called total which then returns the sum total of all price of all individual items.

Access Modifiers.. what?

Access Modifiers are magical words. When we put these magical words in front of properties, they allow us to control the access or visibility of our properties. Let’s look at the access modifiers that PHP offers.

Note: Some other languages may have more of these but since we’re talking from the perspective of PHP, there are 3 main access modifiers according to PHP docs.

  1. Public: Public properties are accessible from anywhere. Even from outside the scope of the class.
  2. Private: We can access these from within the class itself but nowhere else.
  3. Protected: Protected behaves as private unless a class has a child. If a child class of a parent class is present then the child can access the properties and methods of the parent. Think of it like, your parents’ property is somehow your property as well. Their TV is your TV etc.

PHP isn’t fundamentally an Object-Oriented Language

PHP started as a procedural language. That means it used to work on ‘line to line’ basis. And, it relied on well-defined procedures (functions) i.e all the steps a computer must take to reach an output. It is a rather a top-down approach where data moves from function to function from top to bottom of the program.

  1. <?php  
  2. function palindrome($n){  
  3. $number = $n;  
  4. $summation = 0;  
  5. while(floor($number)) {  
  6. $remainder = $number % 10;  
  7. $summation = $summation * 10 + $remainder;  
  8. $number = $number/10;  
  9. }  
  10. return $summation;  
  11. }  
  12. $input = 1235321;  
  13. $num = palindrome($input);  
  14. if($input==$num){  
  15. echo "$input is a Palindrome number";  
  16. else {  
  17. echo "$input is not a Palindrome";  
  18. }  
  19. ?>  

Now, look at the above program to calculate palindrome of a number. It’s a procedural style of coding in PHP where data is flowing from top to bottom using function procedures. There is no class, no object, no inheritance and none of the OOP features we are talking about.

PHP is referred to as a scripting language. So, we can think of PHP as a scripting language in which OOP features were later added. If we have to be specific, these OOP features were added in PHP v5.0. Java, C#, and Smalltalk come to mind when thinking about languages designed specifically keeping Object Orientation in mind.

PHP isn’t fundamentally an OOP language but that doesn’t mean anything other than the fact that now we have a choice on whether to use these features or not whereas with core OOP languages we don’t get to make that choice.

We can work in either way based on the requirements of our projects.

Why and when to use OOP PHP?

  • For a simple project or website, OOP is unnecessary complexity.
  • For a complex project, OOP is necessary to manage the complexity of the project.
  • Projects that require high use of database are complex enough to benefit from an Object Oriented style of programming.
  • But how?
  • Well, we looked at objects. Objects let us have a modular and reusable code. For eg. If we create a class called ‘Student’ with certain properties and methods (function). We can create as many objects from that class as we want.

Let’s start with a blueprint i.e. a class

  • Every class begins with a keyword called ‘class’ followed by a class name.
  • You have curly braces that surround the class definition.

class Book {
// properties and methods of a class
}

class PhoneCamera {
// properties and methods of a class
}

Best practices:

  • Use PasalCase for class name ( i.e camelCase with first letter capitalized) eg. CofidenceLimit, CarRadio etc.
  • Use singular nouns for class names.
  • Keep class definitions in their own separate file.
  • Group them together in a ‘classes’ directory.

PHP functions to know after declaring classes

get_declared_classes()

$classes = get_declared_classes();
echo "All classes: { implode(',' , $classes) } <br>";

The above code will output all the classes declared in the project including the inbuilt ones.

class_exists($class_name)

if (class_exists(Apple)){
echo "This class exists";
} else {
echo "This class does not exist";
}

The above code is checking if the ‘Apple’ class exists or not in our project.

I will end this article here and will write follow up articles following this one.

Note: You will often come across the term ‘4 pillars of OOP’. Click here to learn more about it.

Leave a Comment

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