← Back to Chapters

PHP OOP Static Members

? PHP OOP Static Members

? Quick Overview

Static members in PHP belong to the class itself rather than to any specific object instance. You can access static properties and methods directly using the ClassName:: syntax without creating an object.

? Key Concepts

  • Static properties are shared across all objects of a class
  • Static methods can be called without instantiating the class
  • self:: is used inside the class to access static members
  • ClassName:: is used outside the class

? Syntax & Theory

Static members are declared using the static keyword. Since they are class-level, they cannot access instance-level data using $this.

? View Code Example
// Define a class with static property and method
// Call static methods without creating an object
Counter::increment();
Counter::increment();
// Access static property directly from class
echo Counter::$count;
?>

? Live Output / Explanation

The static property $count starts at 0. Each call to increment() increases it by 1. Since static properties are shared, the final output becomes 2.

? Interactive Concept

Think of static members as a shared whiteboard for the class. Every object sees the same value and modifies the same data.

?️ Use Cases

  • Global counters across objects
  • Utility/helper methods
  • Shared configuration values
  • Application-wide constants

? Tips & Best Practices

  • Static methods cannot access $this
  • Use self:: for internal static access
  • Prefer const for values that never change
  • Avoid overusing static members to reduce tight coupling

? Try It Yourself

  • Create a MathHelper class with static add() and multiply() methods
  • Build a static counter to track object creation
  • Test static properties in parent and child classes
  • Mix static and non-static methods and observe behavior
  • Store shared configuration using static properties