Back to course

Defining Classes and Creating Objects

PHP: The Complete 0 to Hero Bootcamp

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

make . " engine is starting.\n"; } } ?>
  • $this is 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

$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).