Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A class in PHP is a user-defined data type that serves as a blueprint for instantiating objects. It encapsulates state through properties (variables) and behavior through methods (functions), providing the foundational structure for object-oriented programming (OOP) within the language.

Syntax and Declaration

A class is defined using the class keyword followed by a valid identifier (conventionally PascalCase) and a pair of curly braces containing the class members.
class DataProcessor 
{
    // Class members (properties, constants, methods) are defined here
}

Core Components

1. Properties

Properties are variables bound to a class. Modern PHP (7.4+) supports type declarations (typed properties) to enforce data types, though strict type enforcement requires the file-level strict_types declaration. Properties must be declared with a visibility modifier.
class Entity 
{
    public int $id;
    private string $hash;
    protected ?array $metadata = null; // Nullable type with default value
}

2. Constants

Constants are immutable values bound to the class itself rather than an instance. They are declared using the const keyword and are accessed using the Scope Resolution Operator (::).
class Configuration 
{
    public const MAX_RETRIES = 3;
}
// Accessed via: Configuration::MAX_RETRIES

3. Methods

Methods are functions defined within the class. They dictate the behavior of the objects instantiated from the class and can utilize type declarations for both parameters and return values.
class Calculator 
{
    public function add(int $a, int $b): int 
    {
        return $a + $b;
    }
}

4. Static Properties and Methods

Static members belong to the class itself rather than any specific object instance. They are declared using the static keyword. Because they resolve at the class level, they are accessed using the Scope Resolution Operator (::) instead of the object operator (->).
class Cache 
{
    public static string $driver = 'redis';

    public static function getDriver(): string 
    {
        return self::$driver;
    }
}
// Accessed via: Cache::$driver or Cache::getDriver()

5. The Constructor

The __construct() method is a magic method automatically invoked when an object is instantiated. PHP 8.0 introduced Constructor Property Promotion, allowing property declaration and initialization directly within the constructor signature.
class Node 
{
    // PHP 8+ Constructor Property Promotion
    public function __construct(
        public string $name,
        private int $weight = 0
    ) {}
}

Visibility Modifiers

PHP enforces encapsulation through three access modifiers applied to properties, methods, and constants:
  • public: The member is accessible from anywhere (global scope, subclasses, and internally).
  • protected: The member is accessible only within the defining class and any classes that inherit from it.
  • private: The member is accessible exclusively within the defining class.

Context Keywords

PHP provides specific keywords to reference class and object contexts:
  • $this: A pseudo-variable that references the current object instance. Used to access non-static properties and methods ($this->propertyName).
  • self: References the class in which the keyword is written. Used with the Scope Resolution Operator to access static members and constants (self::CONSTANT_NAME).
  • parent: References the immediate parent class in an inheritance hierarchy (parent::__construct()).
  • static: References the class that was initially called at runtime (Late Static Binding).

Instantiation

Objects are created from a class using the new keyword. This allocates memory for the object and triggers the constructor.
$instance = new Node('RootNode', 10);

Advanced Class Modifiers

  • abstract: An abstract class cannot be instantiated directly. It serves as a base class that defines abstract methods (signatures without bodies) which child classes must implement.
  • final: A final class cannot be extended by other classes. When applied to a method, it prevents child classes from overriding that specific method.
  • readonly (PHP 8.2+): Marking a class as readonly implicitly marks all of its instance properties as readonly, preventing modification after initialization and enforcing immutability. (Note: Readonly classes cannot declare static properties).

Comprehensive Structural Example

final class SystemProcess
{
    public const DEFAULT_TIMEOUT = 30;
    private static int $activeProcesses = 0;

    public function __construct(
        private readonly string $processId,
        private int $timeout = self::DEFAULT_TIMEOUT
    ) {
        self::$activeProcesses++;
    }

    public static function getActiveProcessCount(): int
    {
        return self::$activeProcesses;
    }

    public function execute(): bool
    {
        if ($this->validateProcess()) {
            // Execution logic
            return true;
        }
        return false;
    }

    private function validateProcess(): bool
    {
        return !empty($this->processId) && $this->timeout > 0;
    }
}

$process = new SystemProcess('PID_8472');
$process->execute();

$count = SystemProcess::getActiveProcessCount();
Master PHP with Deep Grasping Methodology!Learn More