DEV Community

Cover image for Demystifying Object-Oriented Programming(OOP) in PHP
Brandon Damue
Brandon Damue

Posted on • Edited on

Demystifying Object-Oriented Programming(OOP) in PHP

OOP is a nothing other than a programming technique or paradigm that makes use of classes and objects to write application programs. In an object-oriented program, everything is viewed as a real world object with attributes and behaviours . OOP is a technique that is extensively used in most modern programming languages. Object-oriented programming in PHP started gaining grounds with the release of PHP 5 many years ago. OOP opens the door to cleaner code designs, easier maintenance, and more code reuse.

Understanding OOP can be a bit tricky at first so this article brings to you some OOP core concepts and the goodies that OOP has to offer and how to make use of the OOP features supported by PHP. So let's begin.

OOP Concepts.

Classes

A class is essentially a code blueprint or template from which one or more objects are generated. A class describes what an object can contain, including properties(variables) and functions(methods). The relationship between classes and objects is a strange but wonderful relationship because we describe objects in terms of classes and classes are also often described in terms of objects. Classes are declared with a class keyword and a casual class name. Code associated with a particular class most be enclosed in curly braces.

carbon (2).png

Though the code in the image above is not very useful yet, it is already a legal class from which objects can be generated.

Objects

An object is an instance of a class. It is basically data that has been structured according to the blueprint or template defined by a class. To use the Fruit class we defined above to generate objects, we use the new keyword in conjunction with the class name as show below.

$fruit1 = new Fruit();
$fruit2 = new Fruit();
Enter fullscreen mode Exit fullscreen mode

The only operand in the code above is the new keyword followed by the class name. The code creates two instances of the Fruit class. Although they are functionally identical (that is, empty), $fruit1 and $fruit2 are different objects of the same type generated from a single class.

Properties.

These are special variables that are defined in a class. A property, also known as a member variable, holds data that can vary from object to object. A property in a class looks similar to a standard PHP variable except that, in declaring a property, you must precede the property variable with a visibility keyword(which we will look at in a bit). This can be public, protected, or private, and it determines the scope from which the property can be accessed. Now let's give our Fruit class some properties.

class Fruit {
  // Properties
  public $name;
  public $color;
}
Enter fullscreen mode Exit fullscreen mode

Now the Fruit class has two member variables or properties. To assign a value to a property, we use the following syntax.

$fruit2->name =  "Mango";
Enter fullscreen mode Exit fullscreen mode

You can access property variables and methods on an object-by-object basis using the characters '->' (the object operator) in conjunction with an object variable and property name, like this:

print $fruit->name;
Enter fullscreen mode Exit fullscreen mode

This prints the string Mango. PHP does not force us to declare all our properties in the class. You could add properties dynamically to an object, like this:

$fruit1->shape = "Round";
Enter fullscreen mode Exit fullscreen mode

The method above is not considered good practice in object- oriented programming.

Methods

Methods are special functions declared within a class. Just as properties allow your objects to store data, methods allow your objects to perform tasks or actions. A method declaration resembles a function declaration. The function keyword precedes a method name, followed by an optional list of argument variables in parentheses. The method body is enclosed by braces:

public function myMethod($argument, $another)
    {
   // Some code
 }
//Accessing an object's method
$fruit1->myMethod(...args)
Enter fullscreen mode Exit fullscreen mode

Methods are basically functions as they can take arguments and return a value but unlike regular functions, they must be defined within the body of a class. The visibility of a method can be changed using access modifiers(visibility keywords). If you omit the visibility keyword in your method declaration, the method will be declared public implicitly. It is considered good practice, however, to declare visibility explicitly for all methods. You must use parentheses in your method call as you would if you were calling a function.

Constructor Method

A constructor method is invoked automatically when an object is instantiated. It allows you to initialise an object's properties upon creation of the object. The constructor method is usually named using the following convention.

function __construct() {
  $this->name = $name;
  $this->color = $color;
}
Enter fullscreen mode Exit fullscreen mode

Inheritance

Inheritance is the means by which one or more classes can be derived from a base class.
A class that inherits from another is said to be a subclass of it. This relationship is often described in
terms of parents and children. A child class is derived from and inherits characteristics from the parent. These characteristics consist of both properties and methods. The child class will typically add new functionality to that provided by its parent which is also known as a superclass; for this reason, a child class is said to extend its parent class.

class Person {
  public $name, $address, $age; 
}

class Employee extends Person {
   public $position, $salary;
}
Enter fullscreen mode Exit fullscreen mode

The Employee class has the $position and $salary properties, as well as the $name, $address, and $age properties inherited from the Person class. If a subclass has a property or method with the same name as one in its parent class, the property or method in the subclass takes precedence over the property or method in the parent class. Referencing the property returns the value of the property on the child, while referencing the method calls the method on the child.

Access Modifier

Properties and methods in PHP can contain access modifiers(visibility keywords) that control their visibility or where they can be accessed. There are three access modifiers;

  1. Private: When a property or method in PHP is prefixed with private access modifier, it means that property or method can ONLY be accessed from within the enclosing class meaning even subclasses have no access.

  2. Protected: Properties and methods can only be accessed from within the
    enclosing class and classes that are derived from the enclosing class.

  3. Public: Properties and methods can be accessed from any context. This is the default.

So how is this useful to us? access modifiers allow you to expose only those aspects of a class that
are required by a client. This sets a clear interface for your object. As a general rule, err on the side of
privacy. Make properties private or protected at first and only relax your restriction as needed. Many (if
not most) methods in your classes will be public, but once again, if in doubt, lock it down. A method that provides local functionality for other methods in your class has no relevance to your class’s users so make it private or protected.

Conclusion

The advantages OOP brings to the table are just so enormous that few today would dare to introduce a language that isn't object-oriented. There is more to OOP, concepts which I haven't talked about in this article for the sake of keeping things simple. The sheer fact that OOP presents many advantages doesn't mean that other programming techniques like functional programming have been rendered useless and you should use just the OOP style. No, in my opinion implement a particular technique only if it is ideal for your particular use case. Thanks for reading my article.

Top comments (4)

Collapse
 
jhilgeman profile image
Jonathan H

If the purpose of your article is to "de-mystify" something, then you should try to stay away from uncommon words and concepts that the audience might not know yet. For example:

"OOP is a nothing other than a programming technique or paradigm that makes use of classes and objects to write application programs."

If I were someone who didn't know PHP OOO yet and I started reading, my brain would already be stopping, saying:

"Paradigm? I know that word - it means... Uhh... It means like a... Oh whatever, I'll keep going. Classes and objects?! I don't know what those are. This article must be assuming I know things that I don't know yet, so I'm going to just stop here and not waste my time."

That won't be everybody, of course. Some people will read on to discover what classes are but most beginners get easily frustrated when they feel left behind by the teacher.

Saying "... makes use of THINGS CALLED classes and objects..." tells the reader that you don't expect them to know those concepts yet and an explanation is coming.

Stay away from words you don't hear every day by two or more people, and use words that a 5-year-old can understand whenever possible. Remember that people are learning new words as part of learning this new concept and the more familiar the SURROUNDING terminology, the easier it will be to understand those words.

Consider:
"The versimountable dynamics of programming education"
vs.
"The versimountable ins and outs of teaching programming"

If you were learning "versimountable" (if it were a real word), then the simpler surrounding words help the reader focus on the new term because they're not having to mentally parse the rest of the sentence.

Maybe start your article like this:
"Object-oriented programming (OOP) means thinking about programming the same way we look at the real world. Instead of planning an application by thinking about 'algorithms' and 'functions' , OOP tries to imagine the application as if it existed in the real world. Have a bakery? Well, you need a baker, and an oven, and so on. All of those things are objects, and you define objects by using things called 'classes".

Collapse
 
brandondamue profile image
Brandon Damue

Thank you very much for your review sir. Honestly, this review will help me to start looking things from another perspective. I'll take all you have said into consideration and then try to optimize my writing style. Thanks again

Collapse
 
ibonkonesa profile image
Ibon

Nice aproximation post. Nowadays I think is important to know about Traits. They can be useful in many cases.

Collapse
 
brandondamue profile image
Brandon Damue

Thank you Ibon