PHP Classes and Objects
A class is a blueprint that describes what data and behavior a thing has, while an object is a concrete instance created from that blueprint.
Classes and objects explained
Think of a class as a template and an object as something built from that template. A single 'Car' class describes that every car has a color and a speed and can accelerate, but each actual car you create from it is a separate object with its own color and its own current speed. You write the class once and then make as many objects from it as you need.
In PHP you declare a class with the class keyword followed by a name. By convention class names use PascalCase, meaning each word starts with a capital letter. Inside the class you define properties (the data) and methods (the functions that operate on that data).
Defining a class and creating objects
<?php
class Car
{
public string $color;
public int $speed = 0;
public function accelerate(int $amount): void
{
$this->speed += $amount;
}
}
$first = new Car();
$first->color = "red";
$first->accelerate(30);
$second = new Car();
$second->color = "blue";
echo $first->color . " car at " . $first->speed; // red car at 30
echo "\n";
echo $second->color . " car at " . $second->speed; // blue car at 0
?>Properties and methods
Properties are variables that belong to an object, and methods are functions that belong to a class. You can give a property a type such as string or int and even a default value. Every method can read and change the object's own properties using a special variable called $this.
- Use the new keyword to create an object from a class.
- Access a property or method on an object with the arrow operator ->.
- Inside a method, refer to the current object's own members with $this->.
- Each object keeps its own copy of the property values.
The $this variable
The $this variable is available inside every non-static method and always points to the specific object the method was called on. When you write $this->speed, PHP looks up the speed property of the exact object handling the call, which is why two different cars can hold two different speeds even though they share one class definition.
Reading object state through $this
<?php
class BankAccount
{
public float $balance = 0.0;
public function deposit(float $amount): void
{
$this->balance += $amount;
}
public function describe(): string
{
return "Balance is " . $this->balance;
}
}
$account = new BankAccount();
$account->deposit(150.0);
$account->deposit(50.0);
echo $account->describe(); // Balance is 200
?>