PHP : OOP - Classes and Objects

In PHP, Object-Oriented Programming (OOP) revolves around the concept of classes and objects. Classes are blueprints for creating objects, which are instances of these classes. Here's a guide on how to work with classes and objects in PHP:

1. Creating a Class:

A class is defined using the class keyword followed by the class name. Inside the class, you can define properties (variables) and methods (functions).

Example:

class Car {
    // Properties
    public $brand;
    public $model;

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

2. Creating Objects (Instances):

To create an object (instance) of a class, you use the new keyword followed by the class name and parentheses (if there's a constructor).

Example:

// Create an object of the Car class
$car1 = new Car();

// Set properties of the object
$car1->brand = "Toyota";
$car1->model = "Camry";

// Call a method of the object
echo $car1->displayInfo(); // Output: Brand: Toyota, Model: Camry