Everything up to this point has been procedural — a script running top to bottom, calling functions along the way. Object-oriented programming (OOP) is a different way of organizing code: instead of separate functions and variables floating around, you group related data and behavior together into a single unit called an object.
A class is a blueprint describing what an object of that kind will have and do. An object is one actual instance built from that blueprint. This is exactly like the difference between a house's architectural plan and an actual house built from it — one plan, any number of real houses.
<?php
class Student {
public $name;
public $course;
public function introduce() {
return "Hi, I'm {$this->name}, studying {$this->course}.";
}
}
$student1 = new Student();
$student1->name = "Priya";
$student1->course = "Web Development";
echo $student1->introduce(); // "Hi, I'm Priya, studying Web Development."
?>A property is a variable that belongs to an object ($name, $course above); a method is a function that belongs to one (introduce()). The -> arrow accesses both from outside the class, and $this-> accesses them from inside a method.
Each object created from a class has its own separate copy of every property — changing one object never affects another:
<?php
$student2 = new Student();
$student2->name = "Amit";
$student2->course = "Graphic Design";
echo $student1->name; // still "Priya" — unaffected by $student2
echo $student2->name; // "Amit"
?>More is coming immediately
The next lesson builds directly on this one, adding constructors (setting up an object's starting state automatically), inheritance (one class building on another), and visibility (controlling what's accessible from outside a class).