Classes and objects
What you'll learn:
- describe a class with properties and methods and build objects from it with
new; - set starting values in a constructor and close properties with the word
private; - explain why
$b = $adoes not copy an object, and copy one withclone; - use static properties, class constants,
readonlyand__toString.

Picture the blueprint of a house. It marks the rooms, windows and doors, but nobody can live in a blueprint. From one blueprint you can build as many houses as you like: they are laid out the same way, and each has its own furniture and its own residents.
In PHP the blueprint is called a class, and a house built from it is an object. This picture runs through the whole theme: the blueprint, the houses built from it and the addresses of those houses.
Why do you need a blueprint when data fits in an array? For example, a product in an array: ['title' => 'tea', 'price' => 5]. But an array has weak spots:
- an array does not know which keys it should have, and PHP notices a typo in a key only when the key is read;
- the functions that work with a product live apart from the data and will accept any array.
A class gathers in one place which data an object has and what can be done with it.
Class and object
Let's describe a counter of page visits:
<?php
class Counter
{
public int $value = 0;
}
$visits = new Counter();
$visits->value = $visits->value + 1;
echo $visits->value, "\n"; // 1Let's go through the program step by step:
class Counterdeclares a class namedCounter. Its body sits in curly braces, and the opening brace takes a line of its own.public int $value = 0;declares the property$valueof typeintwith the starting value0. The wordpublicmeans the property can be reached from anywhere in the program.new Counter()builds an object from the class, and it goes into the variable$visits.- The arrow
->reaches a property of that object: read$visits->valueas "thevalueof the object in$visits". - The program adds one to the counter and prints
1.
A class is the description objects are built from: what data they have and what can be done with them. An object is a value built from a class with new, also called an instance of the class. A property is a variable inside an object; it is declared in the class.
Class names start with a capital letter, and so does every following word in the name: Counter, ShoppingCart.
What to know about properties:
- the type goes before the name, as with a function parameter:
int,string,array,?string; - every new object gets the starting value;
- the type is checked on every write, as for a function parameter in coercive mode:
'5'becomes5, while$visits->value = 'many'ends with aTypeError.
One new, one object
Each new builds a new house from the same blueprint. Every object has its own properties:
$home = new Counter();
$about = new Counter();
$home->value = 7;
echo $home->value, ' ', $about->value, "\n"; // 7 0$home and $about are two different objects of the class Counter. The number 7 went only into the property of the object in $home, and the object in $about kept its starting 0.
Interviewers like to ask how a class is different from an object. The answer: a class is a description, and an object is a concrete instance built from it with new. One class can have any number of objects, and each has its own property values.
A method and $this
A class describes not only data but also actions on it. A function declared inside a class is called a method. Here is a shopping cart with the method add:
<?php
class Cart
{
public array $items = [];
public function add(string $item): void
{
$this->items[] = $item;
}
}
$cart = new Cart();
$cart->add('tea');
echo implode(' ', $cart->items), "\n"; // teaLet's take it apart:
public function add(string $item): voiddeclares a method. It works like an ordinary function, only it lives inside the class.$cart->add('tea')calls the method on the object in$cartwith the same arrow->.- Inside a method,
$thisis the object the method was called on. In this call$thisis the same object that sits in$cart. $this->items[] = $item;adds'tea'to theitemsproperty of that object, andecho implode(' ', $cart->items)printstea.
Here the blueprint picture is off. A method is not built into every house: the class describes it once. On every call the method learns from $this which house to work with.
Common mistake
Inside a method, a property is used without $this->:
<?php
class Cart
{
public array $items = [];
public function add(string $item): void
{
$items[] = $item; // ✗
}
}
$cart = new Cart();
$cart->add('tea');
echo count($cart->items), "\n"; // 0The program prints no message at all and outputs 0. As you already know from the functions theme, a function body has its own scope, and so does a method. $items here is a new local variable of the method, not the object's property: PHP creates it, puts 'tea' into it and forgets it after the call.
Inside a method, always reach the object's property through $this: $this->items[] = $item;.
Key points
- A class is a blueprint, and
new Counter()builds a separate object from it with its own properties. - A property is declared in the class with a type and a starting value, and it is read and changed through
->. - A method is a function inside a class, and
$thisin it is the object the method was called on. - Without
$this->, a name inside a method is a local variable, not a property.