Demystifying Object-Oriented Programming(OOP) in PHP
Tags: php, oop, webdev, beginners
Published: 2021-03-21 09:37:50

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](https://cdn.hashnode.com/res/hashnode/image/upload/v1616140740584/kDbQucjKt.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();
```
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;
}
```
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";
```
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;
```
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";
```
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)
```
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;
}
```
### 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;
}
``` 
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.