PHP Classes & Objects

A class is a blueprint; an object is one thing built from it.

PHP
<?php
class Book
{
    public string $title;
    public float  $price;

    public function __construct(string $title, float $price)
    {
        $this->title = $title;
        $this->price = $price;
    }

    public function priceWithVat(): float
    {
        return $this->price * 1.13;
    }
}

$b = new Book("Palpasa Cafe", 480);
echo $b->title;             // Palpasa Cafe
echo $b->priceWithVat();    // 542.4

$this refers to the current object. Note the arrow is ->, and property names after it have no $.

Constructor property promotion (PHP 8+)

The same class, without the repetition:

PHP
<?php
class Book
{
    public function __construct(
        public string $title,
        public float  $price,
    ) {}

    public function priceWithVat(): float
    {
        return $this->price * 1.13;
    }
}

Visibility

Keyword Accessible from
public anywhere
protected the class and its subclasses
private only this class
PHP
<?php
class Account
{
    private float $balance = 0;

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

    public function getBalance(): float
    {
        return $this->balance;
    }
}

Making $balance private is the whole point of encapsulation: the only way to change it is deposit(), which enforces the rule.

Static members

Belong to the class, not to any object. Accessed with ::.

PHP
<?php
class Counter
{
    public static int $count = 0;

    public static function increment(): void
    {
        self::$count++;
    }
}

Counter::increment();
echo Counter::$count; // 1

readonly properties (PHP 8.1+)

PHP
<?php
class Money
{
    public function __construct(
        public readonly int $paisa,
    ) {}
}

$m = new Money(5000);
// $m->paisa = 1; // Error: cannot modify readonly property