HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP Static Methods & Properties

Normally, you need to create an object (instantiate a class) to access its methods and properties. However, by using the **static** keyword, you can create members that belong to the class itself rather than any specific object. This means you can access them without creating an instance of the class.


1. Static Methods

Static methods can be called directly—without creating an instance of the class first. They are often used for utility functions or actions that don't depend on individual object data.

Defining and Calling a Static Method

<?php
    class Greeting {
        public static function welcome() {
            echo "Hello World!";
        }
    }

    // Call static method using ClassName::methodName()
    Greeting::welcome();
?>
Scope Resolution Operator: The double colon (::) is called the **Scope Resolution Operator**. It is used to access static, constant, and overridden members of a class.

2. Static Properties

Static properties belong to the class and are shared across all instances of that class. If you change a static property, it changes for every object created from that class.

<?php
    class pi {
        public static $value = 3.14159;
    }

    // Get static property
    echo pi::$value;
?>

The self Keyword

Inside a class, you cannot use $this to access static members because $this refers to an object instance. Instead, you use the self keyword followed by the scope resolution operator (::).

<?php
    class Counter {
        public static $count = 0;

        public function __construct() {
            self::$count++; // Increment static property on every new object
        }
    }

    $a = new Counter();
    $b = new Counter();
    echo Counter::$count; // Outputs: 2
?>

When to Use Static Members?

  • Utility Classes: For groups of helper functions that don't need to store state (e.g., a MathUtils class).
  • Global Constants/Configs: For data that should be the same across the entire application.
  • Counting Instances: To keep track of how many objects of a class have been created.
  • Singleton Pattern: To ensure only one instance of a class exists throughout the script.
Key Difference:
  • Regular Members: Accessed via $object->member. Requires new.
  • Static Members: Accessed via ClassName::member. Does NOT require new.

Summary

  • static keyword makes a member belong to the class, not an object.
  • Use :: (double colon) to access static members.
  • Use self:: to access static members from within the same class.
  • Static methods cannot access non-static properties (because there is no $this).
  • A class can have both static and non-static members.
Warning: Don't over-use static members. Overusing them can make your code harder to test and move away from pure Object-Oriented principles toward a procedural style.