bhylu.com

Advertisements

PHP Classes and Objects

A class describes a kind of object; an instance has its own state. Start with a small responsibility, such as tracking a requested quantity, rather than putting every application concern in one class.

How it works

Properties hold state and methods describe operations on an instance. $this refers to the receiver of an instance method. Creating two objects with new produces separate instances, whereas assigning one object variable to another normally copies the handle to the same object. Public fields expose the mechanism in this first lab; later examples put validation behind methods or constructors.

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 classes-objects.php
php classes-objects.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+ · classes-objects.php

<?php
declare(strict_types=1);

class Loan {
    public int $quantity = 0;
    public function label(): string { return $this->quantity . " units"; }
}
$first = new Loan();
$second = new Loan();
$first->quantity = 2;
$second->quantity = 5;
echo $first->label(), "\n", $second->label(), "\n";

Expected result

2 units
5 units

Each method reads the property on its own receiver. Changing first does not change second because they were separately created. The example does not yet enforce a positive quantity or check a stock database. A useful class contract should make those responsibilities explicit instead of giving an object a misleadingly broad name.

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