Skip to content
Theory · Classes and objects · lesson 1 of 11

Classes and objects

What you'll learn

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 = $a does not copy an object, and copy one with clone;
  • use static properties, class constants, readonly and __toString.
A house blueprint labelled class and two houses built from it with door plates

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
<?php

class Counter
{
    public int $value = 0;
}

$visits = new Counter();
$visits->value = $visits->value + 1;
echo $visits->value, "\n"; // 1

Let's go through the program step by step:

  1. class Counter declares a class named Counter. Its body sits in curly braces, and the opening brace takes a line of its own.
  2. public int $value = 0; declares the property $value of type int with the starting value 0. The word public means the property can be reached from anywhere in the program.
  3. new Counter() builds an object from the class, and it goes into the variable $visits.
  4. The arrow -> reaches a property of that object: read $visits->value as "the value of the object in $visits".
  5. 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' becomes 5, while $visits->value = 'many' ends with a TypeError.

One new, one object

Each new builds a new house from the same blueprint. Every object has its own properties:

PHP
$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
<?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"; // tea

Let's take it apart:

  1. public function add(string $item): void declares a method. It works like an ordinary function, only it lives inside the class.
  2. $cart->add('tea') calls the method on the object in $cart with the same arrow ->.
  3. Inside a method, $this is the object the method was called on. In this call $this is the same object that sits in $cart.
  4. $this->items[] = $item; adds 'tea' to the items property of that object, and echo implode(' ', $cart->items) prints tea.

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
<?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"; // 0

The 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 $this in it is the object the method was called on.
  • Without $this->, a name inside a method is a local variable, not a property.