PHP Classes and Objects

In PHP, a class is a blueprint for creating objects. An object is an instance of a class, containing properties and methods that define its behavior.

Defining a Class

<?php
class Car {
    public $color;
    public $model;

    public function __construct($color, $model) {
        $this->color = $color;
        $this->model = $model;
    }

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

Creating an Object

<?php
$myCar = new Car("red", "Toyota");
echo $myCar->getDescription();
?>

Output:

This car is a red Toyota.

Explanation: This example demonstrates how to define a class, create an object from that class, and call a method on the object to get its description.