Before a housing estate goes up, an architect draws one plan. Dozens of homes are then built from it; each gets its own address, paint colour and owners, yet all share the same layout. In object-oriented programming, a class plays the role of that plan. It describes what data each instance will hold (its properties) and what each instance can do (its methods), without being any particular instance itself.
Example
class BankAccount {
private float $balance = 0;
public function __construct(public string $owner) {}
public function deposit(float $amount): void {
$this->balance += $amount;
}
}
$account = new BankAccount("Sam");
$account->deposit(50);
Nothing exists in memory until new BankAccount("Sam") runs. That line creates an object; run it again with another name and you get a second, independent account with its own balance.
Ideas that come bundled with classes
- Constructor: a special method that runs when an instance is created, used to set starting values.
- Visibility: keywords like
publicandprivatecontrol which code may read or change a property. Keeping$balanceprivate forces outside code to go throughdeposit(). - Inheritance: one class can extend another, reusing its code while adding or overriding behaviour. A
SavingsAccountmight extendBankAccountand add interest.
Class vs object
Beginners often blur these two. The class is the definition you write once in your source code. An object is a concrete value built from that definition while the program runs, holding its own data. One BankAccount class can produce thousands of accounts, each with a different owner and balance.
Not every language organises code around classes. Java requires them, Python and PHP make them optional, JavaScript added class syntax on top of its older prototype system, and Go and C have no classes at all.
Learn more
- PHP course
- Java course, where every program starts inside a class
- Try the account example in the PHP editor
Last updated