PHP OOP – Classes and Objects

PHP OOP (Object-Oriented Programming) is a programming paradigm that allows developers to create objects that encapsulate data and methods. In PHP, a class is a blueprint for creating objects. An object is an instance of a class.

Here’s an example of a class definition in PHP:

class Car {
    public $make;
    public $model;
    public $year;
    public function __construct($make, $model, $year) {
        $this->make = $make;
        $this->model = $model;
        $this->year = $year;
    public function start() {
        echo "The " . $this->make . " " . $this->model . " is starting...";
    public function stop() {
        echo "The " . $this->make . " " . $this->model . " is stopping...";

In this example, the Car class has three properties ($make, $model, and $year) and two methods (start() and stop()). The __construct() method is a special method that is called when an object of the class is created. It initializes the object’s properties with the values passed to it.

To create an object of the Car class, we can use the new keyword:

$my_car = new Car("Toyota", "Camry", 2018);

This creates a new object of the Car class and initializes its properties with the values passed to the __construct() method.

We can then access the object’s properties and methods using the arrow (->) operator:

echo $my_car->make; // Output: Toyota
$my_car->start(); // Output: The Toyota Camry is starting...

We can create multiple objects of the Car class, each with their own unique properties:

$my_other_car = new Car("Honda", "Accord", 2020);
echo $my_other_car->model; // Output: Accord
$my_other_car->stop(); // Output: The Honda Accord is stopping...

In summary, classes in PHP allow developers to define blueprints for creating objects, and objects allow developers to encapsulate data and behavior into reusable components.