Ugacomp

Introduction to Object-Oriented Programming in PHP

Where necessary, you may need to have access to a VPS server so you can follow how to implement the steps in this article.  You can get a cheaper VPS Server from Contabo with 4vCPU cores, 8GM RAM, and 32TB Bandwidth for less than $5.50 per month. Get this deal here now

Table of Contents

Cloud VPS S

$5.50 Monthly
  • 4 vCPU Cores | 8GB RAM

CLOUD VPS M

$15.50 Monthly
  • 6 vCPU Cores | 16GB RAM

CLOUD VPS L

$17.50 Monthly
  • 8 vCPU Cores | 24GB RAM

Object-Oriented Programming (OOP) is a paradigm that enables developers to structure their code in a more organized and modular way. PHP supports OOP principles, allowing developers to create more maintainable and scalable applications.

Classes and Objects

In PHP, a class is a blueprint for creating objects, which are instances of the class. Let’s start by creating a simple class:

<?php
class Car {
    public $brand;
    public $model;

    function displayInfo() {
        echo "This is a {$this->brand} {$this->model}.";
    }
}

// Creating an object of the Car class
$myCar = new Car();
$myCar->brand = "Toyota";
$myCar->model = "Camry";
$myCar->displayInfo();
?>

Class Definition

To create a class, we use the class keyword, followed by the class name. Inside the class, you define properties and methods.

   <?php
   class MyClass {
       // Properties
       public $property1;
       private $property2;

       // Methods
       public function method1() {
           // code for method1
       }

       private function method2() {
           // code for method2
       }
   }
   ?>
  • public, private, protected: These are access modifiers, controlling the visibility of properties and methods.

Object Creation

Once you have a class, you can create an object (instance of the class) using the new keyword.

   <?php
   // Creating an object
   $myObject = new MyClass();
   ?>
  • $myObject: This is an instance of the MyClass class.

Accessing Properties

You can access the properties of an object using the -> operator.

   <?php
   // Accessing properties
   $myObject->property1 = "Hello";
   echo $myObject->property1;  // Outputs: Hello
   ?>
  • $myObject->property1: Accessing the property1 of $myObject.

Accessing Methods

Methods are functions defined inside a class. You call them using the -> operator as well.

   <?php
   // Calling methods
   $myObject->method1();
   ?>
  • $myObject->method1(): Calling the method1 of $myObject.

Constructor Method

The constructor method __construct() is a special method that gets executed when an object is created. It’s used for initializing object properties.

   <?php
   class MyClass {
       public function __construct() {
           // constructor code
       }
   }
   ?>
  • __construct(): The constructor method.

Encapsulation

Encapsulation is the concept of bundling the data (properties) and methods that operate on the data within a single unit, i.e., a class. We use access modifiers (public, private, protected) to control the visibility of properties and methods.

<?php
class Student {
    private $name;
    private $age;

    public function __construct($name, $age) {
        $this->name = $name;
        $this->age = $age;
    }

    public function displayInfo() {
        echo "Name: {$this->name}, Age: {$this->age}";
    }
}

// Creating an object of the Student class
$student = new Student("John Doe", 20);
$student->displayInfo();
?>

Here, the name and age properties are private, meaning they can only be accessed within the Student class. The constructor (__construct) is used to initialize the object with provided values.

Inheritance

Inheritance is a mechanism that allows a class to inherit properties and methods from another class. The child class can also override or extend inherited methods.

<?php
class Animal {
    public function makeSound() {
        echo "Some generic sound";
    }
}

class Dog extends Animal {
    public function makeSound() {
        echo "Woof! Woof!";
    }
}

// Creating an object of the Dog class
$dog = new Dog();
$dog->makeSound();
?>

In this example, the Dog class extends the Animal class and overrides the makeSound method to provide a specific sound for a dog. When calling $dog->makeSound(), it outputs “Woof! Woof!”.

Polymorphism

Polymorphism allows objects of different classes to be treated as objects of a common base class. This enables flexibility and reusability in code.

<?php
interface Shape {
    public function calculateArea();
}

class Circle implements Shape {
    private $radius;

    public function __construct($radius) {
        $this->radius = $radius;
    }

    public function calculateArea() {
        return pi() * pow($this->radius, 2);
    }
}

class Rectangle implements Shape {
    private $width;
    private $height;

    public function __construct($width, $height) {
        $this->width = $width;
        $this->height = $height;
    }

    public function calculateArea() {
        return $this->width * $this->height;
    }
}

// Using polymorphism
$shapes = [new Circle(5), new Rectangle(4, 6)];

foreach ($shapes as $shape) {
    echo "Area: " . $shape->calculateArea() . "\n";
}
?>

In this example, both Circle and Rectangle implement the Shape interface, ensuring they have a calculateArea method. We then use an array of different shapes and iterate through them, calling the common method calculateArea.

Getter and Setter Methods

Getter and setter methods are used to control access to private properties, providing a controlled way to retrieve and modify them.

<?php
class MyClass {
    private $myProperty;

    public function getMyProperty() {
        return $this->myProperty;
    }

    public function setMyProperty($value) {
        $this->myProperty = $value;
    }
}
?>
  • getMyProperty(): Getter method for accessing myProperty.
  • setMyProperty($value): Setter method for modifying myProperty.

Static Properties and Methods

Static properties and methods belong to the class rather than an instance of the class. They are accessed using the :: notation.

<?php
class MathOperations {
    public static $pi = 3.14;

    public static function calculateCircleArea($radius) {
        return self::$pi * $radius * $radius;
    }
}

// Accessing static property
echo MathOperations::$pi;

// Calling static method
echo MathOperations::calculateCircleArea(5);
?>
  • static: Indicates that a property or method is static.

Visibility Modifiers

Visibility modifiers control the access level of properties and methods. There are three main modifiers: public, private, and protected.

   <?php
   class MyClass {
       public $publicProperty;
       private $privateProperty;
       protected $protectedProperty;

       public function publicMethod() {
           // code for publicMethod
       }

       private function privateMethod() {
           // code for privateMethod
       }

       protected function protectedMethod() {
           // code for protectedMethod
       }
   }
   ?>
  • public: Accessible from anywhere.
  • private: Accessible only within the class.
  • protected: Accessible within the class and its subclasses.

Magic Methods

PHP provides special methods, known as magic methods, that start with a double underscore. These methods are automatically called in certain situations.

   <?php
   class MyClass {
       public function __construct() {
           // constructor code
       }

       public function __toString() {
           return "This is an instance of MyClass";
       }

       public function __get($property) {
           // code to handle property access
       }

       public function __set($property, $value) {
           // code to handle property assignment
       }
   }
   ?>
  • __construct(): Constructor method.
  • __toString(): Converts an object to a string when used in a string context.
  • __get($property): Handles reading inaccessible properties.
  • __set($property, $value): Handles writing to inaccessible properties.

Constants in Classes

You can define constants within a class using the const keyword. Constants are accessed using the :: notation.

   <?php
   class MathOperations {
       const PI = 3.14;

       public function calculateCircleArea($radius) {
           return self::PI * $radius * $radius;
       }
   }

   // Accessing constant
   echo MathOperations::PI;
   ?>
  • const: Defines a class constant.

Abstract Classes and Methods

Abstract classes cannot be instantiated and may contain abstract methods, which must be implemented by child classes.

   <?php
   abstract class Shape {
       abstract public function calculateArea();
   }

   class Circle extends Shape {
       public function calculateArea() {
           // code for calculating circle area
       }
   }
   ?>
  • abstract: Declares an abstract class or method.
  • abstract public function calculateArea();: Declares an abstract method.

Final Classes and Methods

The final keyword can be used to prevent a class from being extended or a method from being overridden.

   <?php
   final class FinalClass {
       // code for FinalClass
   }

   class ChildClass extends FinalClass {
       // This will result in an error
   }
   ?>
  • final class: Declares a final class.
  • final public function method(): Declares a final method.

Each of these concepts adds versatility and structure to your PHP object-oriented code. As you explore them further, you’ll gain a richer understanding of how to design and implement robust PHP applications.

Hire us to handle what you want

Hire us through our Fiverr Profile and leave all the complicated & technical stuff to us. Here are some of the things we can do for you:

  • Website migration, troubleshooting, and maintenance.
  • Server & application deployment, scaling, troubleshooting, and maintenance
  • Deployment of Kubernetes, Docker, Cloudron, Ant Media, Apache, Nginx,  OpenVPN, cPanel, WHMCS, WordPress, and more
  • Everything you need on AWS, IBM Cloud, GCP, Azure, Oracle Cloud, Alibaba Cloud, Linode, Contabo, DigitalOcean, Ionos, Vultr, GoDaddy, HostGator, Namecheap, DreamHost, and more.
 

We will design, configure, deploy, or troubleshoot anything you want. Starting from $10, we will get your job done in the shortest time possible. Your payment is safe with Fiverr as we will only be paid once your project is completed.