PHP OOP: Classes & Objects
Object-Oriented Programming (OOP) organizes code around classes, which act as blueprints for objects. A class defines properties (data) and methods (functions) that describe and control the behavior of its objects.
An object is a specific instance created from a class using the new keyword. Each object has its own copy of the class's properties, while sharing the same defined methods.
class MyClass {
public $property;
function myMethod() { }
}
$obj = new MyClass();Defining a class
A class is defined with the class keyword, followed by its name and a body containing properties and methods, such as class Car { public $color; }.
Creating objects
An object is created with new ClassName(). You access its properties and methods using the -> (arrow) operator, like $car->color or $car->drive().
<?php
class Car {
public $color = "red";
function describe() {
return "This car is " . $this->color;
}
}
$car = new Car();
echo $car->describe();
?>This car is red$this refers to the current object, letting the method access its own property.
<?php
class Counter {
public $count = 0;
function increment() {
$this->count++;
}
}
$c = new Counter();
$c->increment();
$c->increment();
echo $c->count;
?>2Each call to increment() updates the object's own count property using $this.
Key points
- A class is a blueprint for creating objects.
- An object is an instance of a class created with new.
- $this refers to the current object inside a class method.
- The -> operator accesses an object's properties and methods.
