• Home
  • Jobs
  • Courses
  • Certifications
  • Companies
  • Online IDE
  • Login
  • Signup
MYTAT
  • Home
  • Jobs
  • Courses
  • Certifications
  • Companies
  • Online IDE
  • Login
  • Signup
PHP
  • Introduction To PHP
  • PHP Syntax And Basic Concepts
  • PHP Functions And Arrays
  • Working With Forms And User Input
  • PHP Database Interaction
  • PHP Object-Oriented Programming (OOP)
  • Working With Files And Directories
  • PHP Web Development Techniques
  • Error Handling And Debugging In PHP
  • Home
  • Courses
  • PHP
  • PHP Object-Oriented Programming (OOP)

PHP Object-Oriented Programming (OOP)

Previous Next

Introduction To Object-oriented Programming (OOP) Concepts In PHP

Object-Oriented Programming (OOP) is a programming paradigm that revolves around the concept of objects, which are instances of classes. PHP, being an object-oriented scripting language, allows developers to create and manipulate objects, making code more organized, reusable, and easier to maintain. In this guide, we'll introduce you to fundamental OOP concepts in PHP, including classes, objects, inheritance, encapsulation, and polymorphism, with examples.

Classes and Objects

Classes

A class is a blueprint or template for creating objects. It defines the properties (attributes) and behaviors (methods) that objects of that class will have. In PHP, a class is declared using the class keyword.
 

<?php
// Define a class
class Car {
    // Properties (attributes)
    public $brand;
    public $model;
    public $color;

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

    // Method
    public function displayInfo() {
        echo "Brand: $this->brand, Model: $this->model, Color: $this->color";
    }
}
?>
 

Objects

An object is an instance of a class. It represents a specific entity with its own set of properties and behaviors. In PHP, objects are created using the new keyword followed by the class name, optionally passing arguments to the constructor if defined.

<?php
// Create an object of the Car class
$car1 = new Car("Toyota", "Camry", "Red");
$car2 = new Car("Honda", "Civic", "Blue");

// Call the method to display car information
$car1->displayInfo(); // Output: Brand: Toyota, Model: Camry, Color: Red
$car2->displayInfo(); // Output: Brand: Honda, Model: Civic, Color: Blue
?>

Try it now

Inheritance

Inheritance is a mechanism in OOP where a class (subclass or derived class) inherits properties and methods from another class (superclass or base class). It promotes code reusability and allows the creation of a hierarchy of classes.

<?php
// Define a superclass
class Animal {
    public $name;

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

    public function sound() {
        echo "Animal sound";
    }
}

// Define a subclass that inherits from Animal
class Dog extends Animal {
    public function sound() {
        echo "Bark";
    }
}

// Create objects of both classes
$animal = new Animal("Animal");
$dog = new Dog("Dog");

// Call the sound method
$animal->sound(); // Output: Animal sound
$dog->sound();    // Output: Bark
?>

Try it now

Encapsulation

Encapsulation is the bundling of data (attributes) and methods that operate on the data into a single unit, called a class. It hides the internal state of an object and only exposes the necessary functionalities through methods, providing better control over access to data and preventing direct manipulation.

<?php
// Define a class with encapsulation
class BankAccount {
    private $balance;

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

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

    public function withdraw($amount) {
        if ($amount <= $this->balance) {
            $this->balance -= $amount;
        } else {
            echo "Insufficient funds";
        }
    }

    public function getBalance() {
        return $this->balance;
    }
}

// Create an object of the BankAccount class
$account = new BankAccount(1000);

// Deposit and withdraw money
$account->deposit(500);
$account->withdraw(200);

// Get the current balance
echo "Current balance: $" . $account->getBalance(); // Output: Current balance: $1300
?>

Try it now

Polymorphism

Polymorphism allows objects of different classes to be treated as objects of a common superclass. It enables flexibility in code design and promotes code reuse by allowing methods to behave differently based on the object's type.

<?php
// Define a superclass
class Shape {
    public function calculateArea() {
        return 0;
    }
}

// Define subclasses that inherit from Shape
class Circle extends Shape {
    private $radius;

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

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

class Rectangle extends Shape {
    private $length;
    private $width;

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

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

// Create objects of both classes
$circle = new Circle(5);
$rectangle = new Rectangle(4, 6);

// Call the calculateArea method
echo "Area of the circle: " . $circle->calculateArea();       // Output: Area of the circle: 78.539816339745
echo "Area of the rectangle: " . $rectangle->calculateArea(); // Output: Area of the rectangle: 24
?>

Try it now



Practice Excercise Practice now

Creating Classes And Objects In PHP

In PHP, classes and objects are fundamental concepts of object-oriented programming (OOP). They allow developers to create reusable code structures, encapsulate data, and define behaviors associated with entities in their applications.

Defining a Class

A class serves as a blueprint or template for creating objects. It defines the properties (attributes) and behaviors (methods) that objects of that class will have.

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

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

    public function displayInfo() {
        return "Brand: $this->brand, Model: $this->model, Color: $this->color";
    }
}
?>
 

In the above example:

  • We define a class named Car using the class keyword.
  • The class has three properties: $brand, $model, and $color.
  • We define a constructor method __construct() to initialize object properties when objects of this class are created.
  • We also define a method displayInfo() to display information about a car.

Creating Objects

Once a class is defined, we can create objects (instances) of that class using the new keyword followed by the class name.

<?php
$car1 = new Car("Toyota", "Camry", "Red");
$car2 = new Car("Honda", "Civic", "Blue");
?>
 

In the above example:

  • We create two objects of the Car class: $car1 and $car2.
  • Each object has its own set of properties ($brand, $model, $color) initialized with the provided values.
  • The __construct() method is automatically called when each object is created, initializing its properties accordingly.

Accessing Object Properties and Methods

Once objects are created, we can access their properties and methods using the object operator ->.

<?php
echo $car1->displayInfo(); // Output: Brand: Toyota, Model: Camry, Color: Red
echo $car2->displayInfo(); // Output: Brand: Honda, Model: Civic, Color: Blue
?>
 

In the above example:

  • We call the displayInfo() method on each object to display information about the cars.
  • Each object's method operates on its own set of properties, providing specific information for that object.

Benefits of Classes and Objects

Using classes and objects in PHP offers several advantages:

  • Modularity and Reusability: Classes encapsulate related data and behaviors, promoting code reusability and modularity.
  • Encapsulation: Object properties can be encapsulated, allowing for data hiding and access control.
  • Abstraction: Classes provide a level of abstraction, allowing developers to focus on the interface rather than the implementation details.
  • Inheritance: Classes support inheritance, enabling code reuse and facilitating the creation of hierarchies of related classes.
  • Polymorphism: Objects of different classes can be treated uniformly through polymorphism, allowing for flexible and extensible code.

In conclusion, classes and objects are powerful features of PHP that enable developers to build modular, maintainable, and scalable applications. They provide a structured way to organize code, encapsulate data, and define behaviors, leading to cleaner and more efficient development processes.



Practice Excercise Practice now

Implementing Inheritance, Encapsulation, And Polymorphism In PHP Classes

Inheritance in PHP:

Inheritance is a fundamental concept in object-oriented programming (OOP) where a class inherits properties and methods from another class. In PHP, this is achieved using the extends keyword. Let's consider an example:

<?php

// Parent class
class Animal {
    protected $name;

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

    public function speak() {
        echo "{$this->name} speaks";
    }
}

// Child class inheriting from Animal
class Dog extends Animal {
    public function wagTail() {
        echo "{$this->name} wags tail";
    }
}

// Creating instances
$animal = new Animal("Generic Animal");
$dog = new Dog("Buddy");

// Calling methods
$animal->speak(); // Output: Generic Animal speaks
$dog->speak();    // Output: Buddy speaks
$dog->wagTail();  // Output: Buddy wags tail
?>

Try it now

In this example, the Dog class inherits the name property and the speak() method from the Animal class.

Encapsulation in PHP:

Encapsulation refers to the bundling of data and methods that operate on the data into a single unit, i.e., a class. Access to the data and methods is typically restricted to prevent misuse. In PHP, encapsulation is achieved using access modifiers like public, protected, and private. Let's see an example:

<?php

class BankAccount {
    private $balance;

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

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

    public function withdraw($amount) {
        if ($this->balance >= $amount) {
            $this->balance -= $amount;
            return $amount;
        } else {
            return "Insufficient funds";
        }
    }

    public function getBalance() {
        return $this->balance;
    }
}

// Creating an instance
$account = new BankAccount(1000);

// Accessing methods
echo "Current Balance: $" . $account->getBalance(); // Output: Current Balance: $1000
$account->deposit(500);
echo "<br>";
echo "After Deposit: $" . $account->getBalance(); // Output: After Deposit: $1500
echo "<br>";
echo "Withdrawn: $" . $account->withdraw(200); // Output: Withdrawn: $200
echo "<br>";
echo "Final Balance: $" . $account->getBalance(); // Output: Final Balance: $1300
?>

Try it now
 

In this example, the balance property is encapsulated within the BankAccount class, and access to it is controlled through public methods like deposit(), withdraw(), and getBalance().

Polymorphism in PHP:

Polymorphism allows objects of different classes to be treated as objects of a common superclass. This allows for flexibility in programming. In PHP, polymorphism is often achieved through method overriding. Let's illustrate this:

<?php

// Parent class
class Shape {
    public function calculateArea() {
        return 0;
    }
}

// Child classes
class Circle extends Shape {
    private $radius;

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

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

class Rectangle extends Shape {
    private $length;
    private $width;

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

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

// Creating instances
$circle = new Circle(5);
$rectangle = new Rectangle(4, 6);

// Calling the same method name on different objects
echo "Circle Area: " . $circle->calculateArea(); // Output: Circle Area: 78.539816339745
echo "<br>";
echo "Rectangle Area: " . $rectangle->calculateArea(); // Output: Rectangle Area: 24
?>

Try it now


In this example, both the Circle and Rectangle classes have a calculateArea() method, but each class implements it differently. When calling calculateArea() on objects of these classes, polymorphism ensures that the appropriate implementation is used based on the object type.



Practice Excercise Practice now

Previous Next
COMPANY
  • About us
  • Careers
  • Contact Us
  • In Press
  • People
  • Companies List
Products
  • Features
  • Coding Assessments
  • Psychometric Assessment
  • Aptitude Assessments
  • Tech/Functional Assessments
  • Video Assessment
  • Fluency Assessment
  • Campus
 
  • Learning
  • Campus Recruitment
  • Lateral Recruitment
  • Enterprise
  • Education
  • K 12
  • Government
OTHERS
  • Blog
  • Terms of Services
  • Privacy Policy
  • Refund Policy
  • Mart Category
Partner
  • Partner Login
  • Partner Signup

Copyright © RVR Innovations LLP 2025 | All rights reserved - Mytat.co is the venture of RVR Innovations LLP