Learn/PHP/10. Structuring data with classes
Lesson 10 of 15
Sign in

PHP, lesson 10

Structuring data with classes

Associative arrays are handy, but they have no fixed shape: nothing stops you from writing $pet["hungr"] by mistake. A class defines a type with known properties and the methods that work on them. Each object created from a class has its own copy of the data.

A first class

  • new Rectangle(3, 4) creates an object and calls the constructor, __construct().
  • $this is the object the method is working on.
  • -> reaches a property or method of an object.
  • Properties are declared with a type (public float $width;), so PHP rejects a wrong value.

Constructor property promotion

Declaring a property, accepting a parameter and copying one into the other is so common that PHP 8 has a shortcut. Put the visibility in front of a constructor parameter and PHP declares and assigns the property for you:

2 exercises to try what you just read.

Exercise 1

Garden plots

Press Ctrl Enter or Check to test your code.

Exercise 2

Virtual pet

Press Ctrl Enter or Check to test your code.

This class behaves exactly like the longer one above.

Visibility

  • public: usable from anywhere.
  • protected: usable inside the class and its subclasses.
  • private: usable only inside this class.

Make properties private when the class has rules to protect, and offer methods that enforce those rules. A bank account, for example, shouldn't let outside code set a negative balance directly:

readonly properties

A readonly property can be set once, inside the class, and never changed afterwards. That suits value objects such as a coordinate or a money amount:

Writing readonly class Point makes every property readonly at once.

Turning objects into text

Define __toString() to control what echo $object prints. Methods whose names start with two underscores are magic methods: PHP calls them for you at specific moments.

Static methods and constants

static methods and class constants belong to the class itself rather than to one object. You call them with ::, for example Temperature::fromFahrenheit(98.6) or Pet::MAX_LEVEL. A static "named constructor" like that is a neat way to offer several ways to create an object.

PHP 8.4 also added property hooks, which let a property run code when it's read or written, but plain properties and methods cover everything you need here.

Further reading

  • Classes and objects: the basics
  • Constructors and constructor promotion
  • Properties and readonly
  • Visibility
  • Magic methods

Finish the Plot class. area() returns width × length, fence() returns the perimeter and isSquare() returns whether both sides are equal. Each input line holds a width and a length (whole numbers); the starter prints one line per plot:

Sample input:

Sample output:

Write a Pet class. The constructor takes the name; hunger and mood both start at 5 and are private. Add three public methods:

  • feed() lowers hunger by 3
  • play() raises mood by 2 and raises hunger by 1
  • nap() raises mood by 1

Neither value may go below 0 or above 10: clamp after every change (max(0, min(10, $v))). Add __toString() returning <name>: hunger <hunger>, mood <mood>.

The first input line is the name; each following line is a command (feed, play or nap). The starter runs the commands and echoes the pet at the end.

Sample input:

Sample output:

<?php

class Rectangle
{
    public float $width;
    public float $height;

    public function __construct(float $width, float $height)
    {
        $this->width = $width;
        $this->height = $height;
    }

    public function area(): float
    {
        return $this->width * $this->height;
    }
}

$box = new Rectangle(3, 4);
echo $box->area(), "\n";    // 12
echo $box->width, "\n";     // 3
<?php

class Rectangle
{
    public function __construct(
        public float $width,
        public float $height,
    ) {}
}
<?php

class Account
{
    private int $balance = 0;

    public function deposit(int $amount): void
    {
        if ($amount <= 0) {
            throw new InvalidArgumentException("deposit must be positive");
        }
        $this->balance += $amount;
    }

    public function balance(): int
    {
        return $this->balance;
    }
}
<?php

final class Point
{
    public function __construct(
        public readonly int $x,
        public readonly int $y,
    ) {}
}

$p = new Point(2, 3);
// $p->x = 5;   // Error: Cannot modify readonly property
// inside class Rectangle
public function __toString(): string
{
    return "{$this->width}x{$this->height}";
}
area=12 fence=14 square=no
3 4
5 5
area=12 fence=14 square=no
area=25 fence=20 square=yes
Biscuit
play
play
feed
Biscuit: hunger 4, mood 9