Skip to main content

Lesson 2 of 7

Visibility, Static Members & Constants

Visibility (public/protected/private) is the primary mechanism for encapsulation - hiding internal implementation details. Static methods and properties belong to the class itself, not any instance. Understanding when to use static - and when not to - is key to writing testable PHP.

12 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Visibility, Static & Constants

Visibility, Static & Constants
<?php
declare(strict_types=1);

class User {
    public const ROLES = ["guest", "author", "editor", "admin"];

    // public   - accessible anywhere
    // protected - accessible in class + subclasses
    // private  - accessible in this class only
    // readonly - can only be set in constructor (PHP 8.1)

    private static int $instanceCount = 0;  // shared across all instances

    public function __construct(
        public readonly int    $id,
        private string         $email,
        private string         $passwordHash,
        protected string       $role = "guest",
    ) {
        self::$instanceCount++;
    }

    // ── Static factory method - named constructor ──────────────
    public static function create(string $email, string $password): static {
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            throw new InvalidArgumentException("Invalid email: $email");
        }
        return new static(
            id:           0,
            email:        strtolower(trim($email)),
            passwordHash: password_hash($password, PASSWORD_BCRYPT),
        );
    }

    // ── Getter - controlled access to private property ───────
    public function getEmail(): string { return $this->email; }
    public function getRole(): string  { return $this->role; }

    // ── Password verification - encapsulates implementation ───
    public function verifyPassword(string $password): bool {
        return password_verify($password, $this->passwordHash);
    }

    // ── Static - class-level utility, no instance needed ──────
    public static function getInstanceCount(): int {
        return self::$instanceCount;
    }

    public static function isValidRole(string $role): bool {
        return in_array($role, self::ROLES, true);
    }

    // ── Magic methods ─────────────────────────────────────────
    public function __toString(): string {
        return sprintf("User<%d:%s>", $this->id, $this->email);
    }

    // Prevent serialization of sensitive data
    public function __sleep(): array {
        return ["id", "email", "role"];  // passwordHash NOT included
    }
}

// Usage
$user = User::create("alice@example.com", "secret123");
echo User::getInstanceCount();     // 1
echo User::ROLES[3];               // "admin"
var_dump(User::isValidRole("god")); // false

// ── Late Static Binding - static:: vs self:: ──────────────────
class BaseModel {
    protected static string $table = "base";

    public static function getTable(): string {
        return static::$table;   // static:: = the CALLED class (late binding)
        // self:: = always BaseModel - wrong in subclasses
    }
}

class PostModel extends BaseModel {
    protected static string $table = "posts";
}

echo BaseModel::getTable();   // "base"
echo PostModel::getTable();   // "posts" (correct with static::, wrong with self::)

Quick Quiz

Tip

Tip

Practice Visibility Static Members Constants in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for Visibility, Static Members & Constants

Practice Task

Note

Practice Task - (1) Write a working example of Visibility Static Members Constants from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with Visibility Static Members Constants is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/7 done