In PHP, a class is a blueprint for creating objects. It defines the properties (attributes) and methods (functions) that objects of that class will have. An object, on the other hand, is an instance of a class. It’s a concrete entity that has its own set of attribute values and can perform actions defined by the methods of its class.
Here’s an example of a class and an object in PHP:
class Car { // Properties (attributes) public $brand; public $model; public $year; // Methods (functions) public function startEngine() { return "Engine started!"; } public function stopEngine() { return "Engine stopped!"; } } // Creating an object (instance) of the Car class $myCar = new Car(); // Setting attribute values $myCar->brand = "Toyota"; $myCar->model = "Camry"; $myCar->year = 2022; // Accessing methods and properties of the object echo $myCar->startEngine(); // Output: "Engine started!" echo "<br>"; echo $myCar->brand; // Output: "Toyota"
In this example, the Car
class is defined with properties ($brand
, $model
, and $year
) and methods (startEngine()
and stopEngine()
). An object $myCar
is created using the new
keyword. The object’s attributes are set, and its methods are called to perform actions.
Classes provide a way to encapsulate data and behavior into reusable structures. Objects allow you to work with instances of those classes, each having its own distinct properties and behavior. This concept is fundamental to object-oriented programming (OOP), which is widely used in PHP and many other programming languages.