Tutorials Logic, IN info@tutorialslogic.com

PHP OOP Basics: Classes, Objects, Constructors, and Encapsulation

Object Model

A class defines a type with state and behavior. An object is one instance of that class with its own property values.

Use a class when data and rules belong together. A few unrelated utility functions do not become better merely because they are placed in a class.

PHP Class

A constructor establishes initial state. Visibility expresses which operations are public and which details remain internal to the class.

Course Progress Class

Course Progress Class
<?php
declare(strict_types=1);

final class CourseProgress
{
    public function __construct(
        public readonly string $course,
        private int $completed = 0
    ) {
    }

    public function completeLesson(): void
    {
        $this->completed++;
    }

    public function summary(): string
    {
        return "{$this->course}: {$this->completed} complete";
    }
}

PHP Object

new calls the constructor and returns an object. The -> operator accesses instance methods and public properties. Each object keeps separate instance state.

Two Independent Objects

Two Independent Objects
<?php
$php = new CourseProgress('PHP');
$sql = new CourseProgress('SQL');

$php->completeLesson();
$php->completeLesson();
$sql->completeLesson();

echo $php->summary() . PHP_EOL;
echo $sql->summary();
Output
PHP: 2 complete
SQL: 1 complete

Encapsulation

Private state can change only through class methods, which provides one place to enforce rules. A getter for every property is not meaningful encapsulation if callers can still create invalid combinations.

Prefer behavior names such as completeLesson() or changeEmail() over generic setCompleted() when a rule belongs to the operation.

Class or Function

Situation Likely choice
Stateless calculation Function
One data record with no behavior Array or small value object
State with invariants and operations Class
Several interchangeable implementations Interface plus classes

Identity and Invariants

Two objects created from the same class have separate identity even when their properties currently match. The === operator checks whether two variables reference the same object; == compares properties according to PHP object comparison rules. Domain equality is often clearer as a named method that compares the fields the business considers significant.

A constructor should reject an impossible starting state. Every public method should preserve the same invariant afterward. Readonly properties are useful for values that must not be reassigned after initialization, but a readonly property that refers to an object does not make that nested object deeply immutable.

  • Use typed properties so invalid assignments fail close to their source.
  • Expose behavior that expresses a rule instead of public setters for every field.
  • Keep infrastructure such as database access outside a small domain value object.
  • Use clone deliberately when a new object identity is required.

Class and Object Check

0 of 2 checked

Q1. What does a class define?

Q2. Why keep completed private?

Object Design Failures

  • Public mutable state

    Protect invariants with private properties and behavior-specific methods.
  • Constructor accepts invalid values

    Validate required ranges and combinations before assigning state.
  • Utility class with no state

    Prefer a namespaced function when no object identity or contract is needed.

Try this next

Model One Rule

0 of 2 completed

  1. Keep balance private and reject a withdrawal larger than the balance.
  2. Create two accounts and prove that changing one does not change the other.
Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.