Classes, properties and methods
A class is a blueprint: it declares the data an object holds (properties) and what it can do (methods). new ClassName() creates an object (an instance). Inside a method, $this is the object the method was called on, and -> reaches a property or method. Note there is no $ after the arrow: $this->balance, not $this->$balance. Class names are PascalCase, one class per file in real projects.
<?php
class BankAccount
{
public string $owner = '';
public float $balance = 0;
public function deposit(float $amount): void
{
$this->balance += $amount;
}
public function describe(): string
{
return "{$this->owner} has {$this->balance}";
}
}
$acc = new BankAccount();
$acc->owner = 'Asha';
$acc->deposit(500);
$acc->deposit(250.5);
echo $acc->describe(), "\n";
$other = new BankAccount(); // a separate object, its own data
$other->owner = 'Ravi';
echo $other->describe(), "\n";
var_dump($acc instanceof BankAccount);
echo get_class($acc), "\n";Asha has 750.5
Ravi has 0
bool(true)
BankAccountAdd a withdraw(float $amount): bool method that refuses (returns false) when the balance is too low.
$user['email']). A class gives the same data a name, typed fields your editor can autocomplete, and methods that keep the rules next to the data. Rule of thumb: once the same array shape appears in three places, make it a class.