Thuta Learning
PHP
AdvancedProgrammingBeginner

PHP Classes and Objects

PHPLesson 2535 min

What you'll walk away with

  • Declare a class with typed properties and a promoted constructor, and create objects with new
  • Use public, protected and private visibility (and readonly) to keep an object's rules in one place
  • Choose between an interface, an enum and a trait for a given design problem
  • Explain why $b = $a does not copy an object and how clone is different

Explain it simply

Explain it simply

A class is a blueprint, and an object is one real thing built from that blueprint. A Course class describes what every course has (a title, a number of lessons) and what every course can do (summarise itself). Writing new Course('PHP', 30) then builds one actual course that holds its own title and lesson count.

The useful part is that data and the code that works on it live together. Instead of passing a loose array to ten different functions, you pass around one object that knows how to behave, and you decide which parts outsiders may touch with public, protected and private.

Problem → Why → Solution

The problem: plain arrays have no rules

Early PHP code usually models a thing with an associative array. It is quick, but the array is just a bag: any code can add keys, overwrite values with the wrong type or store a nonsense number, and PHP will not complain. A typo such as 'balanse' quietly creates a second key while the real balance stays untouched, so the bug shows up three pages later.

array-account.php
<?php
// An account as a plain array: nothing protects the rules
$account = ['owner' => 'Aye', 'balance' => 5000];

$account['balanse'] = 100;      // typo: silently creates a new key
$account['balance'] = -999999;  // nobody stops a negative balance
$account['balance'] = 'lots';   // or a string

echo $account['balance'];       // lots

Why a class fixes this

A class turns the bag into a contract. Typed properties reject the wrong type, a private property cannot be changed from outside, and the balance can only change through methods that check the rules first. When a bug appears you look inside the class instead of at every file that ever touched the array.

Core concept: class, object and visibility

A class declares properties (the data) and methods (the behaviour). Inside a method, $this is the object the method was called on, so $this->title reads this object's own title. You call a method with the arrow: $course->summary(). The double colon :: is for things that belong to the class itself, such as constants and static methods, and mixing the two up is one of the most common beginner errors.

The constructor, __construct(), runs exactly once when you write new. It receives the starting state, and that is the right place to validate it, because an object that cannot be created in an invalid state never needs defensive checks later. Constructor property promotion, available since PHP 8.0, lets you put a visibility keyword in front of a constructor parameter: private string $title declares the property and assigns the argument to it in a single step. The example in this lesson uses it, and it saves about six lines of boilerplate per class.

promotion.php
<?php
class LongForm
{
    private string $title;
    private int $lessons;

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

class Promoted
{
    public function __construct(private string $title, private int $lessons) {}
}

print_r(new LongForm('PHP', 30));
print_r(new Promoted('PHP', 30));

In the code above, print_r shows both objects holding the same two private properties, so the promoted form is equivalent to the long one. Visibility decides who may touch a property or method: public means anyone, protected means the class and its subclasses, and private means only the class itself. Start with private and open things up only when a real caller needs it. The reason is not secrecy: every public member is a promise you must keep when you refactor, while private members can change freely.

Add types to every property and parameter. A typed property such as private int $lessons refuses a value that cannot be converted, and with declare(strict_types=1) it refuses anything that is not an int. Mark a property readonly when it should be set exactly once; PHP then throws an Error on any later change, even from inside the class. Finally, objects behave like handles: $b = $a gives you two names for the same object, and you need clone to get an independent copy.

Mental model: blueprint, object, door
  1. class = blueprint, new = one object
  2. Constructor sets the starting state
  3. Methods use $this to reach that state
  4. private keeps the front door narrow

Outsiders talk to an object through its public methods; the fields stay behind the door.

General pattern

pattern.php
<?php
class ClassName
{
    public function __construct(private Type $property) {}

    public function method(): ReturnType
    {
        return $this->property;
    }
}

$object = new ClassName($value);

A class holds properties and methods. A promoted constructor parameter (private Type $property) declares a property and fills it in one go. $this->property reaches the object's own data, and new ClassName(...) builds an object.

Example: a Course object that summarises itself

This is the smallest useful class: two private properties filled by a promoted constructor and one public method that builds a sentence. Notice that the code outside the class never touches title or lessons directly; it only calls summary().

Also note the double quotes: inside them PHP replaces $this->title and $this->lessons with the property values.

php
<?php
class Course
{
    public function __construct(
        private string $title,
        private int $lessons
    ) {}

    public function summary(): string
    {
        return "$this->title — $this->lessons lessons";
    }
}

$course = new Course('PHP', 30);
echo $course->summary();

Code breakdown

  1. Line 2class Course

    Declares the blueprint. By convention class names use StudlyCaps, each class lives in its own file, and the file is named after the class.

  2. Line 5private string $title,

    A promoted parameter. The private keyword makes PHP declare a title property and assign the argument to it. Reading $course->title from outside the class throws an Error.

  3. Line 7) {}

    The constructor body is empty because promotion already did the assignments. If you need validation, this is where it goes.

  4. Line 11return "$this->title — $this->lessons lessons";

    Inside a method $this is the object itself, so every object uses its own title and lessons. The return type says string, so returning another type would cause a TypeError.

  5. Line 15$course = new Course('PHP', 30);

    new calls the constructor with 'PHP' and 30 and hands back a fresh object. Another new with different arguments gives a second object with its own state.

  6. Line 16echo $course->summary();

    The arrow -> calls the method and echo prints the result. The output is PHP — 30 lessons.

You should see
PHP — 30 lessons

Protecting rules: readonly and constructor validation

A class earns its keep when it refuses invalid states. The Money class below validates in the constructor, makes both properties readonly and never changes itself: plus() builds a new Money instead of mutating. Objects like this are called value objects, and they are easy to reason about because nothing can alter them behind your back. final stops anyone from extending the class and weakening those rules.

money.php
<?php
declare(strict_types=1);

final class Money
{
    public function __construct(
        public readonly int $amount,
        public readonly string $currency,
    ) {
        if ($amount < 0) {
            throw new InvalidArgumentException('Amount cannot be negative');
        }
    }

    public function plus(Money $other): Money
    {
        if ($other->currency !== $this->currency) {
            throw new InvalidArgumentException('Currency mismatch');
        }
        return new Money($this->amount + $other->amount, $this->currency);
    }

    public function __toString(): string
    {
        return number_format($this->amount) . ' ' . $this->currency;
    }
}

$price = new Money(2500, 'MMK');
$total = $price->plus(new Money(1500, 'MMK'));
echo $price, ' + 1,500 MMK = ', $total, "\n";

try {
    $price->amount = 1;
} catch (Error $e) {
    echo get_class($e), ': ', $e->getMessage(), "\n";
}

try {
    new Money(-5, 'MMK');
} catch (InvalidArgumentException $e) {
    echo 'Rejected: ', $e->getMessage(), "\n";
}

Compare each line of output with the code. The second line is an Error PHP raises itself, with the message Cannot modify readonly property Money::$amount, and the third is a value the constructor refused. The throw and catch here are explained fully in the next lesson; for now read throw as 'stop here and report a problem'.

Interfaces, enums and traits

PHP gives you three tools that look similar but solve different problems. An interface lists the methods a class promises to have, so code can accept any Shape without caring which class it receives. An enum is a fixed set of named values, replacing loose strings like 'draft' that can be mistyped. A trait is a bundle of methods and properties copied into a class, useful when unrelated classes need the same helper code but share no parent.

ToolUse it whenExample
interfaceMany classes must promise one set of methodsShape, Logger
enumA value must be one of a few named choicesStatus::Draft, Role::Admin
traitUnrelated classes need to share codeHasTimestamps
extendsA genuine is-a relationship with shared codeDog extends Animal
shapes.php
<?php
interface Shape
{
    public function area(): float;
}

final class Circle implements Shape
{
    public function __construct(private float $radius) {}

    public function area(): float
    {
        return M_PI * $this->radius ** 2;
    }
}

final class Rectangle implements Shape
{
    public function __construct(private float $width, private float $height) {}

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

function describe(Shape $shape): string
{
    return sprintf('%s with area %.2f', $shape::class, $shape->area());
}

foreach ([new Circle(1.5), new Rectangle(3, 4)] as $shape) {
    echo describe($shape), "\n";
}

describe() accepts the interface rather than a concrete class, so adding a Triangle later changes no existing code. $shape::class gives the object's class name. Run the enum and trait examples below too: enum cases are objects, from() throws a ValueError for an unknown value, and tryFrom() returns null instead.

status-enum.php
<?php
enum Status: string
{
    case Draft = 'draft';
    case Published = 'published';
    case Archived = 'archived';

    public function label(): string
    {
        return ucfirst($this->value);
    }

    public function isVisible(): bool
    {
        return $this === self::Published;
    }
}

final class Post
{
    public function __construct(
        public readonly string $title,
        public Status $status = Status::Draft,
    ) {}
}

$post = new Post('Hello');
echo $post->status->label(), "\n";

$post->status = Status::from('published');
$visible = var_export($post->status->isVisible(), true);
echo $post->status->label(), ' visible? ', $visible, "\n";

var_dump(Status::tryFrom('deleted'));

foreach (Status::cases() as $case) {
    echo $case->name, '=', $case->value, "\n";
}

try {
    Status::from('deleted');
} catch (ValueError $e) {
    echo $e->getMessage(), "\n";
}
trait.php
<?php
trait HasTimestamps
{
    private ?string $touchedAt = null;

    public function touch(string $when): void
    {
        $this->touchedAt = $when;
    }

    public function touchedAt(): string
    {
        return $this->touchedAt ?? 'never';
    }
}

final class Article
{
    use HasTimestamps;
}

final class Comment
{
    use HasTimestamps;
}

$article = new Article();
$comment = new Comment();
$article->touch('2026-01-05');
echo 'Article: ', $article->touchedAt(), "\n";
echo 'Comment: ', $comment->touchedAt(), "\n";

Static members, constants and __toString

Some things belong to the whole class rather than to each object. const and static declare these class-level members, reached with :: as in self::MAX_LESSONS or Course::created(). A static factory method (fromArray) combined with a private constructor lets the class control exactly how objects get built. __toString() is the method PHP calls automatically when an object is used where a string is needed, such as with echo.

static-members.php
<?php
final class Course
{
    public const MAX_LESSONS = 40;
    private static int $created = 0;

    private function __construct(
        public readonly string $title,
        public readonly int $lessons,
    ) {
        self::$created++;
    }

    public static function fromArray(array $data): self
    {
        $lessons = min((int) ($data['lessons'] ?? 0), self::MAX_LESSONS);
        return new self(trim($data['title'] ?? 'Untitled'), $lessons);
    }

    public static function created(): int
    {
        return self::$created;
    }

    public function __toString(): string
    {
        return "{$this->title} ({$this->lessons} lessons)";
    }
}

$a = Course::fromArray(['title' => ' PHP Basics ', 'lessons' => 30]);
$b = Course::fromArray(['lessons' => 99]);
echo $a, "\n", $b, "\n";
echo 'Created: ', Course::created(), ' of max ', Course::MAX_LESSONS, "\n";

try {
    new Course('Direct', 1);
} catch (Error $e) {
    echo $e->getMessage(), "\n";
}

The last line shows the private constructor blocking an attempt to call new Course(...) from outside the class. Objects can therefore only come through fromArray(), so rules such as trimming the title and capping the lesson count cannot be bypassed.

Objects are handles: assignment and clone

Copying an integer with $b = $a gives two independent values. Objects are different: the variable holds a handle (an identifier) to the object, so $b = $a creates two names for one object. Passing an object to a function works the same way, and a change made inside the function is visible to the caller. Use clone when you need an independent copy. == compares property values, while === asks whether both sides are the very same object.

handles.php
<?php
final class Counter
{
    public int $count = 0;

    public function increment(): void
    {
        $this->count++;
    }
}

$a = new Counter();
$b = $a;            // a second name for the same object
$b->increment();
echo "a=$a->count b=$b->count\n";

$c = clone $a;      // a real, independent copy
var_dump($a == $c, $a === $c);   // same values, but not the same object
$c->increment();
echo "a=$a->count c=$c->count\n";

In real projects

Where this shows up in real projects

Almost every PHP framework is built from classes. Laravel's Eloquent models, Symfony services and Composer packages all expose classes, and the PSR-4 autoloading from the namespaces lesson maps one class to one file. In a typical request a controller object receives a Request and calls a service object, and the service uses a repository object that talks to the database through PDO; the next lessons build exactly that shape.

Passing collaborators into constructors (dependency injection) makes each class easy to test, because a test can hand in a fake. Enums are now a common way to model statuses and roles, and readonly value objects such as Money, Email or DateRange prevent whole families of bugs: a function that takes an Email cannot be handed an unvalidated string by accident.

Common mistakes

Common mistakes

1. Reading a private property from outside

When title is private, echo $course->title; throws Error: Cannot access private property Course::$title. Rather than making the property public, add a method that gives callers what they actually need (such as summary()), or use public readonly when it is plain data that must never change.

2. Calling an instance method with ::

Writing $course::summary() or Course::summary() fails with Error: Non-static method Course::summary() cannot be called statically. Use -> on an object and keep :: for constants and static methods.

3. Creating a property by typo

Writing $course->typo = 5; makes PHP 8.2 and later print Deprecated: Creation of dynamic property Course::$typo is deprecated. The script keeps running, so the bug can stay hidden. Declare and type every property up front, and do not ignore deprecation notices.

4. Assuming $b = $a makes a copy

After $b = $a, changing $b also changes $a, because both names point at one object. Use clone for a real copy, or design value objects so that their changing methods return a new object.

Best practices

Best practices

  • Type every property and avoid public mutable state; make anything that never changes readonly.
  • Make classes final by default and open them up only when you deliberately design them for extension.
  • For code reuse, prefer composition (an object holding another object) and interfaces over inheritance.
  • Model fixed choices such as a status with an enum instead of loose strings.

Mini challenge

Mini challenge: a BankAccount that protects its balance

Build a BankAccount class for a small savings app. The balance must never be negative, and nobody outside the class may set it directly.

  • A promoted constructor with a readonly string owner and a private int balance that starts at 0 (reject a negative opening balance)
  • deposit(int $amount) accepts only positive amounts; withdraw(int $amount) refuses amounts above the balance
  • Invalid calls throw InvalidArgumentException, and the calling code catches it and prints the message
  • A balance() method returns the current balance; also print the Error message you get when assigning to the balance property directly
bank-account.php
<?php
declare(strict_types=1);

final class BankAccount
{
    // TODO: promoted constructor: public readonly string $owner, private int $balance = 0
    //       (reject a negative opening balance)

    // TODO: deposit(int $amount): void  - positive amounts only, otherwise throw

    // TODO: withdraw(int $amount): void - never more than the balance, otherwise throw

    // TODO: balance(): int
}

$account = new BankAccount('Aye', 1000);

// TODO: run these four calls, each inside try/catch (InvalidArgumentException), and print
//       "<label>: ok, balance N"  or  "<label>: rejected - <message>"
//       deposit 500, withdraw 2000, deposit -50, withdraw 300

// TODO: try to assign $account->balance directly and print the Error message

Expected: deposit 500: ok, balance 1500 withdraw 2000: rejected - Cannot withdraw 2000 from 1500 deposit -50: rejected - Deposit must be positive, got -50 withdraw 300: ok, balance 1200 Direct write blocked: Cannot access private property BankAccount::$balance

Show hint

Put a guard check at the top of deposit() and withdraw() and throw when it fails, then change $this->balance. You can put the four calls into an array of callbacks (fn() => ...) and run them in a foreach inside try/catch.

Show solution
bank-account.php
<?php
declare(strict_types=1);

final class BankAccount
{
    public function __construct(
        public readonly string $owner,
        private int $balance = 0,
    ) {
        if ($balance < 0) {
            throw new InvalidArgumentException('Opening balance cannot be negative');
        }
    }

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

    public function withdraw(int $amount): void
    {
        if ($amount <= 0 || $amount > $this->balance) {
            throw new InvalidArgumentException(
                "Cannot withdraw $amount from {$this->balance}"
            );
        }
        $this->balance -= $amount;
    }

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

$account = new BankAccount('Aye', 1000);

$attempts = [
    'deposit 500'   => fn() => $account->deposit(500),
    'withdraw 2000' => fn() => $account->withdraw(2000),
    'deposit -50'   => fn() => $account->deposit(-50),
    'withdraw 300'  => fn() => $account->withdraw(300),
];

foreach ($attempts as $label => $attempt) {
    try {
        $attempt();
        echo "$label: ok, balance {$account->balance()}\n";
    } catch (InvalidArgumentException $e) {
        echo "$label: rejected - {$e->getMessage()}\n";
    }
}

try {
    $account->balance = 1_000_000;
} catch (Error $e) {
    echo 'Direct write blocked: ', $e->getMessage(), "\n";
}

Quick quiz 1 / 3

Given class A { public function __construct(private int $n) {} }, what happens with $a = new A(5); echo $a->n;?

Quick quiz 2 / 3

A Counter object starts with $count = 0 and increment() adds 1. What does $a = new Counter(); $b = $a; $b->increment(); echo $a->count; print?

Quick quiz 3 / 3

Money has public readonly int $amount and a method add(int $n): void { $this->amount += $n; }. What happens when add() is called on an existing object?

What to remember

  • A class bundles properties (data) and methods (behaviour), new builds an object, and inside a method $this is that object.
  • Constructor promotion (private string $title) declares and assigns a property in one step, and the constructor is the right place to validate.
  • Start with private, make anything unchanging readonly, and make classes final.
  • Interfaces are promises, enums are fixed choices and traits share code; objects are handles, so use clone when you want a copy.

PHP Classes and Objects — The Basics — PHP

PHP Classes and Objects — The Basics — PHP

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

PHP Classes and Objects | Thuta Learning