> ## 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.

# PHP Class

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.

```php theme={"dark"}
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.

```php theme={"dark"}
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 (`::`).

```php theme={"dark"}
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.

```php theme={"dark"}
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 (`->`).

```php theme={"dark"}
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.

```php theme={"dark"}
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.

```php theme={"dark"}
$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

```php theme={"dark"}
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();
```

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor PHP Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
