Intern
What is the difference between a class and an object in object-oriented programming?
sobes.tech AI
Answer from AI
A class is a template or blueprint for creating objects, defining their properties (variables) and behavior (methods).
An object is a specific, tangible instance of a class. Each object has its own property values but shares the behavior definition specified by the class.
Example:
<?php
// Definition of the Car class
class Car {
// Properties
public $brand;
public $model;
// Method
public function startEngine() {
echo "Engine started!";
}
}
// Creating an object (instance of the Car class)
$myCar = new Car();
// Assigning values to the object's properties
$myCar->brand = "Toyota";
$myCar->model = "Camry";
// Calling the object's method
$myCar->startEngine();
?>
In this example:
Caris the class.$myCaris an object, an instance of theCarclass.$brandand$modelare class/object properties.startEngine()is a class/object method.
You can create many objects from one class, each with unique property values.