32. Defining Classes and Creating Objects
We start the OOP journey by defining the blueprint (Class) and then making instances of that blueprint (Objects).
Defining a Class
A class is defined using the class keyword. By convention, class names are capitalized using PascalCase (e.g., Car, UserAccount).
php
<?php class Car { // 1. Properties (data/attributes) public $color; public $make; // 2. Methods (actions/functions) public function startEngine() { echo "The " . $this->make . " engine is starting.\n"; } } ?>$thisis a special variable that refers to the specific instance of the object currently executing the method.
Creating Objects (Instantiation)
An object is created using the new keyword.
php
<?php // Create two separate objects (instances) of the Car class $car1 = new Car(); $car2 = new Car(); // Accessing and setting properties using the arrow operator -> $car1->color = "Red"; $car1->make = "Tesla"; $car2->color = "Blue"; $car2->make = "BMW"; // Calling methods $car1->startEngine(); // Output: The Tesla engine is starting. $car2->startEngine(); // Output: The BMW engine is starting. ?>Each object ($car1 and $car2) has its own independent copy of the properties (color and make).