bhylu.com

Advertisements

PHP Static Members

Static members belong to a class-level context rather than a particular instance. They can express pure named operations or shared execution-local state, but their lifetime must be understood.

How it works

A static method has no $this receiver. Class constants can name stable values, while static properties hold mutable state according to the runtime’s execution model. Ordinary request-oriented PHP does not turn a static counter into durable cross-request storage. Prefer explicit dependencies for mutable business state, especially when tests need isolation or long-running workers reuse a process.

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 static-members.php
php static-members.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+ · static-members.php

<?php
declare(strict_types=1);

class LoanCode {
    public const PREFIX = "LN";
    private static int $issued = 0;
    public static function next(): string { return self::PREFIX . "-" . ++self::$issued; }
}
echo LoanCode::next(), "\n";
echo LoanCode::next(), "\n";

Expected result

LN-1
LN-2

The counter is shared between these two calls in one script execution. It is intentionally not a production identifier generator: another execution can start again at one, and concurrent processes do not coordinate through this property. A database-generated key or another deliberate ID scheme is needed for durable uniqueness.

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