Static Methods & Properties
Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 17 of 91.
Just as properties can be static, methods can also belong to the class itself rather than to individual objects. Static methods are called on the class directly, without needing to create an instance first.
You declare a static method using the static keyword and call it with the class name and :: operator:
<?php
class MathHelper {
public static function add($a, $b) {
return $a + $b;
}
public static function multiply($a, $b) {
return $a * $b;
}
}
echo MathHelper::add(5, 3) . "\n";
echo MathHelper::multiply(4, 2);
Output:
8
8Static methods work well with static properties. A common pattern is using a static method to manage shared class data:
<?php
class Counter {
private static $count = 0;
public static function increment() {
self::$count++;
}
public static function getCount() {
return self::$count;
}
}
Counter::increment();
Counter::increment();
echo Counter::getCount();
Output:
2Notice that static methods cannot use $this because there's no object instance. They can only access static properties and other static methods using self::.
Key Point: Static methods are useful for utility functions that don't need object state, or for managing class-level data. They provide functionality without requiring object instantiation.
Challenge
EasyLet's build an ID generator system that uses static methods and properties to create unique identifiers without needing to instantiate objects.
You'll create two files to organize your code:
IdGenerator.php— Define anIdGeneratorclass that manages unique ID generation using only static members. The class should have a private static property$lastIdstarting at0and a private static property$prefixset to"ID". Create a static methodgenerate()that increments the last ID and returns a formatted string combining the prefix and the new ID (like"ID1","ID2", etc.). Add a static methodsetPrefix($newPrefix)that changes the prefix, and a static methodgetLastId()that returns the current value of$lastId.main.php— Include the IdGenerator class file. Generate two IDs using the default prefix and print each one on its own line. Then change the prefix to"USER"using the static method, generate two more IDs, and print each one. Finally, print the last ID number by calling the appropriate static method.
Remember that static methods are called directly on the class using ClassName::methodName(), and inside the class you access static properties with self::$propertyName. Since there's no object instance, you cannot use $this in static methods.
Your output should show the progression of IDs with different prefixes, demonstrating how static properties maintain their values across multiple method calls.
Cheat sheet
Static methods belong to the class itself and are called without creating an instance. Declare them using the static keyword and call them with the class name and :: operator:
<?php
class MathHelper {
public static function add($a, $b) {
return $a + $b;
}
}
echo MathHelper::add(5, 3); // 8
Static methods can access static properties using self:::
<?php
class Counter {
private static $count = 0;
public static function increment() {
self::$count++;
}
public static function getCount() {
return self::$count;
}
}
Counter::increment();
echo Counter::getCount(); // 1
Static methods cannot use $this because there's no object instance. They can only access static properties and other static methods using self::.
Static methods are useful for utility functions that don't need object state, or for managing class-level data without requiring object instantiation.
Try it yourself
<?php
// Include the IdGenerator class file
require_once 'IdGenerator.php';
// TODO: Generate two IDs using default prefix and print each on its own line
// TODO: Change the prefix to "USER" using the static method
// TODO: Generate two more IDs and print each on its own line
// TODO: Print the last ID number using the appropriate static method
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe $this KeywordMethodsPropertiesConstructor (__construct)Destructor (__destruct)Recap - Simple Calculator4Inheritance
Basic InheritanceThe parent:: KeywordMethod OverridingThe final KeywordAbstract ClassesRecap - Employee Hierarchy7Encapsulation
Public, Protected, PrivateAccess Modifiers in DepthGetters and SettersInformation HidingConstructor Promotion (8.0)Recap - Student Records System2Namespaces & Autoloading
Introduction to NamespacesThe use KeywordPSR-4 Autoloading StandardComposer AutoloaderRecap - Organized Project5Interfaces & Contracts
Introduction to InterfacesImplementing InterfacesMultiple Interface ImplementInterface vs Abstract ClassType Hinting with InterfacesRecap - Shape Calculator8Magic Methods
Magic Methods Introduction__toString & __debugInfo__get, __set, __isset, __unset__call & __callStatic__clone & Object Cloning__serialize & __unserializeRecap - Custom Collection11Type System & Error Handling
Type DeclarationsNullable TypesUnion & Intersection TypesException ClassesCustom Exception HierarchyTry, Catch, FinallyRecap - Form Validator14Project: Library Management
Project OverviewBook and User Classes3Class Properties
Instance vs Static PropertiesConstants in ClassesStatic Methods & PropertiesPrivate & Protected PropertiesReadonly Properties (PHP 8.1)Recap - Bank Account Manager6Polymorphism
Method Overriding RevisitedPolymorphism via InterfacesType Hinting & Union TypesLate Static BindingRecap - Payment Processor9Traits
Introduction to TraitsUsing Multiple TraitsTrait Conflict ResolutionAbstract Methods in TraitsTraits vs Inheritance12Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern