bhylu.com

Advertisements

PHP Encapsulation

Private state and narrow methods let an object protect a rule. Callers ask for an operation instead of editing internal counters in an arbitrary order.

How it works

public members are part of the accessible interface. private members belong to the declaring class, while protected members also participate in inheritance rules. Visibility is a maintainability boundary, not encryption. A stock object can prevent a local count from going negative, but it does not coordinate different PHP requests or replace a transactional database constraint.

Run it locally

Run this complete source locally with PHP 8.2 or newer. Save it using the filename shown and run the command below. PHP is not currently available in Bhylu’s browser playground. Apache and MySQL are not needed for an ordinary CLI example.

php -l encapsulation.php
php encapsulation.php

Download this source as a local PHP lab file. Keep lab files separate from the Bhylu project and production data.

Example

PHP 8.2+ · encapsulation.php

<?php
declare(strict_types=1);

class Stock {
    private int $available;
    public function __construct(int $available) {
        if ($available < 0) throw new InvalidArgumentException("Negative stock");
        $this->available = $available;
    }
    public function reserve(int $count): bool {
        if ($count <= 0 || $count > $this->available) return false;
        $this->available -= $count;
        return true;
    }
    public function remaining(): int { return $this->available; }
}
$stock = new Stock(5);
echo $stock->reserve(3) ? "Reserved\n" : "Rejected\n";
echo $stock->reserve(3) ? "Reserved\n" : "Rejected\n";
echo $stock->remaining(), "\n";

Expected result

Reserved
Rejected
2

The first operation leaves two. The second request fails without changing that state. A caller cannot directly assign the private property through the public interface. Tests should check not only the boolean result but also that rejection leaves the invariant unchanged.

Check the official PHP manual for detailed version and API contracts.