OBJECT ORIENTED PROGRAMMING IN PHP

php logoThe first step in understanding OOP is to understand classes and objects. A class is a template of code used to create one or more objects. Imagine the prototype of a car, just as cars (objects) are created from the prototype (class), so in OOP from classes are created objects that can be, most often are, distinct from each other.
A class is defined by the keyword class, it can contain letters and numbers but cannot begin with a number. The notation for class names is pascal-case (Like camel-case only the first letter is also capitalized).

OBJECTS

An object represents data that has been structured according to class. An object is said to be an instance of its class. Just as objects (cars) are generated from a vehicle prototype, so objects are generated from classes. Each object is in its own right, for example we can customize a car, circles, color etc. Thus the variables $corsoPHP and $corsoJS are two separate objects created by the same template i.e. the class course but still different from each other.

PROPERTIES AND METHODS

A property is nothing more than a variable inserted within the class, while a method is a function inserted within the class. A property must be declared with its scope of visibility, which can be, public, private, protected. Properties declared as public are accessible both inside and outside the class, while with private or protected they are accessible only inside the classes.

Copy to Clipboard

METHODS

Methods allow objects to perform tasks. These are special functions declared within the class; as with functions we can do type hinting. $this represents the reference to the object created by the class.

Copy to Clipboard

THE CONSTRUCTOR METHOD

There are two types of methods: explicitly invoked methods and methods that are executed by PHP at certain times. Methods that are performed automatically are called magic methods. The first magical method we are going to analyze is __construct (constructor). Thanks to the constructor we can initialize an object with certain values. This method is automatically invoked by PHP when creating the object (when we use the new operator).

Copy to Clipboard

CONSTRUCTOR PROPERTY PROMOTION

PHP 8 further improves the readability of the code. Instead of declaring public properties and assigning them in the constructor we can use a shortened syntax (see code below).

Copy to Clipboard

FURTHER INFORMATION

Object-oriented programming (OOP) in PHP is a programming paradigm that uses objects and classes to organize code in a more structured and modular way.
OOP makes it possible to create reusable components and handle increasing complexity in software development projects.
The following is an in-depth description of the key concepts of OOP in PHP.

1. Classes and Objects

– Class : A class is a template or blueprint that defines the properties (variables) and methods (functions) that an object created from it will have.
In PHP, a class is defined using the keyword class, followed by the class name and the curly brackets that enclose the properties and methods.

class Automobile {
      public $brand;
      public $model;

      public function startMotor() {
         echo“The engine is started.
      }

}

– Object : An object is an instance of a class.
Once a class is defined, objects can be created using the new keyword.

$miaAuto = new Automobile();

$miaAuto->brand =“Fiat“;

$miaAuto->model =“500“;

$miaAuto->startMotor(); // Output: The engine is started.

2. Properties and Methods.

Properties: Properties are variables defined within a class.
Each object has its own set of values for these properties.

class Person

{

      public $first name;

      public $surname;

}

Methods: Methods are functions defined within a class.
These methods can operate on the object’s properties or perform other actions.

class Person {

       public $first name;

       public $lastname;

     public function nameComplete() {
         return $this->firstname .” ” . $this->lastname;
     }
}

In the example above, $this is a special keyword that refers to the current instance of the class.

3. Visibility: Public, Private and Protected

Visibility defines the accessibility of the properties and methods of a class:

Public: Properties and methods declared as public are accessible from anywhere in the program.

class Product { public $price; }

Private : Properties and methods declared as private are accessible only within the class in which they are defined.

class BankAccount {
       private $balance;

       public function deposit($amount) {
            $this->balance += $amount;
       }
}

Protected : Properties and methods declared as protected are accessible only within the class in which they are defined and by derived classes (subclasses).

class BankAccount { protected $balance; }

4. Constructor and Destroyers

– Constructor : A constructor is a special method that is called automatically when a new instance of a class is created.
It is used to initialize the properties of the object.

class Automobile {
     public $brand;
     public $model;

     public function __construct($brand, $model) {
        $this->brand = $brand;
        $this->model = $model;
     }
}

$auto = new Automobile(“Fiat“,“500“);

– Destroyer : A destructor is a special method that is called automatically when an object is destroyed.
It is used to perform cleanup operations, such as closing connections or releasing resources.

class Automobile {

     public function __destruct()

     {

        echo“The Automobile object was destroyed.“;

     }

}

5. Inheritance

Inheritance is a mechanism that allows one class (subclass) to inherit properties and methods from another class (superclass).
In PHP, one class inherits from another using the extends keyword.

class Vehicle {
      public $type;

      public function start() {
         echo“The vehicle is started.
      }

}

class Automobile extends Vehicle {
      public $brand;
      public $model;
{

$auto = new Automobile();
$auto->start(); // Output: The vehicle is started.

6. Interfaces

Interfaces in PHP define a contract that classes must abide by.
An interface specifies the methods that must be implemented by any class that “implements” the interface.

interface Vehicle {
        public function start();
}

class Automobile implements Vehicle {
      public function start() {
         echo“The car is started.“;
      }
}

7. Trait

Traits are a mechanism for reusing code within different classes.
A trait is similar to a class, but is designed to group reusable methods together.

trait Greeting {
       public function greet() {
             echo“Hello!
       }

}

class Person {
      use Greeting;
{

$p = new Person();
$p->greet(); // Output: Hello!

Conclusion

OOP in PHP provides a powerful and flexible set of tools for building modular, scalable and maintainable applications.
Understanding and correctly applying the principles of OOP is critical for any PHP developer who wants to create robust, high-quality software.

LINKS TO PREVIOUS POSTS

THE PHP LANGUAGE

LINK TO THE CODE ON GITHUB

GITHUB