How to Create Classes and Objects in PHP

Object-Oriented Programming (OOP) is a core concept in modern PHP development that allows developers to write modular, reusable code. This article provides a straightforward guide on how to define a class and instantiate an object in PHP, complete with clear explanations and practical code examples.

Defining a Class in PHP

A class is a blueprint or template used to create objects. It defines properties (variables) and methods (functions) that the resulting objects will have.

To define a class in PHP, use the class keyword followed by the name of the class (typically written in PascalCase) and a set of curly braces.

<?php
class Car {
    // Properties (variables)
    public $color;
    public $model;

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

    // Method (function)
    public function getDescription() {
        return "This car is a " . $this->color . " " . $this->model . ".";
    }
}
?>

Instantiating an Object in PHP

An object is an individual instance of a class. Once a class is defined, you can create multiple unique objects from that single blueprint.

To instantiate an object, use the new keyword followed by the class name. If the class has a constructor method (__construct), you must pass the required arguments inside the parentheses.

<?php
// Instantiate an object of the Car class
$myCar = new Car("red", "Toyota");

// Accessing properties and methods using the -> operator
echo $myCar->color; // Outputs: red
echo "\n";
echo $myCar->getDescription(); // Outputs: This car is a red Toyota.
?>

Key Takeaways