PHP classes and objects for beginners

Intermediate  Nov 3, 2026

Group data and behaviour together, and use a class to wrap database work.

PHP classes and objects for beginners
The steps of this tutorial at a glance.
The steps of this tutorial at a glance.

A first class

<?php
class User
{
    public function __construct(
        public string $name,
        private string $email
    ) {}

    public function email(): string
    {
        return $this->email;
    }

    public function greeting(): string
    {
        return 'Hello ' . $this->name;
    }
}

$u = new User('Ali', 'ali@example.com');
echo $u->greeting();
How the code in this section fits into the page.
How the code in this section fits into the page.

Visibility

  • public: usable from anywhere.
  • private: only inside the class.
  • protected: inside the class and its children.
The main points of this section.
The main points of this section.

Static helpers

class Str
{
    public static function slug(string $s): string
    {
        return trim(preg_replace('/[^a-z0-9]+/', '-', strtolower($s)), '-');
    }
}
echo Str::slug('Hello World!');   // hello-world

A small repository

class UserRepo
{
    public function __construct(private PDO $pdo) {}

    public function find(int $id): ?array
    {
        $s = $this->pdo->prepare('SELECT * FROM users WHERE id = ?');
        $s->execute([$id]);
        return $s->fetch() ?: null;
    }
}

All the SQL for users now lives in one place, which makes changes and testing easier.

Tip

Start small. Use classes where they remove repetition, not everywhere.

More tutorials