Open In App

What is Static Keyword in PHP?

Last Updated : 19 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In PHP, the static keyword is used to declare class members (properties and methods) that belong to the class itself rather than to instances of the class (objects). Static members are shared across all instances of the class and can be accessed without creating an object of the class.

Syntax:

class MyClass {
public static $count = 0;

public static function incrementCount() {
self::$count++;
}
}

MyClass::incrementCount(); // Call static method
echo MyClass::$count; // Access static property


Static Properties:

  • Static properties are declared using the static keyword and are shared among all instances of the class.
  • They retain their value throughout the execution of the script.

Static Methods:

  • Static methods are declared using the static keyword and can be called directly on the class without the need to instantiate an object.
  • They cannot access non-static (instance) properties or methods directly.

Use Cases:

  • Static members are useful for defining utility methods or properties that are shared across all instances of the class.
  • They are commonly used for counters, caching mechanisms, or helper functions.
  • Overuse of static members can lead to tight coupling and make code harder to test and maintain.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads