Home » PHP Static Methods: A Tutorial with Examples

PHP Static Methods: A Tutorial with Examples

In PHP, static methods are functions within a class that do not require an instance to be accessed.

These methods belong to the class itself rather than a specific object and are useful when a method performs a task independent of instance properties.

This tutorial will cover:

1. What Are Static Methods in PHP?

A static method is declared using the static keyword inside a class. Unlike regular methods, you don’t need to create an object to call a static method.

Example: Basic Static Method

<?php
class Calculator {
    public static function add($a, $b) {
        return $a + $b;
    }
}

// Calling the static method without creating an object
echo Calculator::add(5, 10); // Output: 15
?>
  • add() is a static method, so we call it using ClassName::methodName().
  • No object instantiation is needed.

2. Defining and Calling Static Methods

Static methods can perform tasks that don’t depend on object properties.

Example: Creating and Calling Static Methods

<?php
class Utility {
    public static function greet($name) {
        return "Hello, " . $name . "!";
    }
}

// Calling the static method
echo Utility::greet("John"); // Output: Hello, John!
?>
  • Declaring a static method: Use public static function methodName().
  • Calling a static method: Use ClassName::methodName().

3. Accessing Static Properties in Static Methods

Static methods can only access static properties.

Example: Using Static Properties in Static Methods

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

    public static function increment() {
        self::$count++;  // Access static property using self::
        return self::$count;
    }
}

// Calling static method multiple times
echo Counter::increment(); // Output: 1
echo Counter::increment(); // Output: 2
?>
  • Static methods cannot use $this.
  • Use self::$propertyName to access static properties.

4. Static vs Non-Static Methods

Static methods belong to the class, while non-static methods belong to an instance.

Example: Static vs Non-Static Method

<?php
class Example {
    public static function staticMethod() {
        return "This is a static method!";
    }

    public function nonStaticMethod() {
        return "This is a non-static method!";
    }
}

// Calling static method
echo Example::staticMethod(); 

// Creating an object for a non-static method
$obj = new Example();
echo $obj->nonStaticMethod();
?>
  • Static methods can be called without an object.
  • Non-static methods require an object ($obj->method()).

5. Calling Static Methods Dynamically

You can call static methods dynamically using a variable class name.

Example: Calling Static Methods Dynamically

<?php
class Logger {
    public static function logMessage($message) {
        echo "Log: " . $message;
    }
}

$className = "Logger";
$className::logMessage("This is a log entry!"); // Output: Log: This is a log entry!
?>
  • $className::methodName() calls the static method dynamically.

6. Using self and static Keywords

  • self:: refers to the current class (ignores inheritance).
  • static:: refers to the child class (used in inheritance).

Example: self vs static in Inheritance

<?php
class ParentClass {
    public static function show() {
        return "Called from " . self::class;
    }
}

class ChildClass extends ParentClass {
    public static function show() {
        return "Called from " . static::class;
    }
}

// Calling methods
echo ParentClass::show(); // Output: Called from ParentClass
echo ChildClass::show();  // Output: Called from ChildClass
?>
  • self::class refers to the parent class.
  • static::class refers to the child class.

7. When to Use Static Methods

Use static methods when: A method doesn’t require object properties (e.g., utility functions).
The method should be shared across all instances.
You need a helper function (e.g., formatting, logging).

Avoid static methods when:
The method modifies object-specific data.
You need polymorphism (static methods cannot be overridden the same way as instance methods).

8. Real-World Examples of Static Methods

Example 1: A Static Helper Class

<?php
class Formatter {
    public static function toUpperCase($text) {
        return strtoupper($text);
    }
}

echo Formatter::toUpperCase("hello world"); // Output: HELLO WORLD
?>
  • Useful for formatting text without needing an object.

Example 2: Database Connection Using Static Method

<?php
class Database {
    private static $connection = null;

    public static function getConnection() {
        if (self::$connection === null) {
            self::$connection = new PDO("mysql:host=localhost;dbname=test", "root", "");
        }
        return self::$connection;
    }
}

// Using static method to get the database connection
$db = Database::getConnection();
?>
  • The static method ensures only one database connection is created.

Example 3: Logging Messages

<?php
class Logger {
    public static function log($message) {
        file_put_contents("log.txt", date("Y-m-d H:i:s") . " - " . $message . PHP_EOL, FILE_APPEND);
    }
}

Logger::log("User logged in.");
?>
  • Logs messages to a file without needing an instance.

Conclusion

Static methods belong to the class, not an object.
They are called using ClassName::methodName().
Use self:: for static properties within the same class.
Use static:: for inheritance.
Best used for utility functions, logging, and single-instance access (e.g., databases).

Static methods increase efficiency by allowing direct access to shared functionality without requiring an object instance.

You may also like