Static Method in PHP: How They Work in Classes

php static methods

PHP static method lets you call functions without an object. In this article, we will cover the following topics:

  • The definition of static methods.
  • The difference between static methods and instance methods in PHP.
  • Access the static methods within the class in PHP.

Let’s start with the definition.

What Are Static Methods in PHP?

A static method in PHP belongs to a class, not an object. You can call it without an instance. Use the static keyword before the method inside a class to define it. You can call it with the scope resolution operator (::).

Here is how you define it:

class MathHelper {
    public static function add_calc($a, $b) {
        return $a + $b;
    }
}

You can call it through the scope resolution operator:

// Call without an object
echo MathHelper::add_calc(5, 3); // Output: 8

Here, you don’t need to create an object to use add_calc() method. Use static methods when the function does not depend on object properties.

Let’s move on to the following section to see the difference between static methods vs. Instance methods in PHP.

Static Methods vs. Instance Methods

In the following example, we collect two methods in one class:

class ExampleTwoBoth {
    public static function staticMethod() {
        return "This is a static method.";
    }

    public function instanceMethod() {
        return "This is an instance method.";
    }
}

Static methods:

  • Belong to the class,not an object.
  • Use the static keyword.
  • Called with the scope resolution operator (::).
  • Do not access $this because they do not depend on object properties.

Let’s call the staticMethod from the above example:

echo ExampleTwoBoth::staticMethod();
// Output: This is a static method.

Instance methods

  • Belong to an object of a class.
  • Require an instance to call them.
  • Can access $this to work with object properties.

Here’s how you call it:

$CLSInstance = new ExampleTwoBoth();
echo $CLSInstance->instanceMethod();
// output: This is an instance method.

So, how do you access static methods within the same class? Let’s learn that in the following section.

Access Static Methods Within the Same Class

Use self keyword that refers to the current class to call a static method inside the same class.

Here is an example:

class MyCalculator {
    public static function add_calc($a, $b) {
        return $a + $b;
    }

    public static function sumExample() {
        return self::add_calc(5, 3);
    }
}

echo MyCalculator::sumExample(); // Output: 8

The sumExample() calls add_calc() with self::add_calc(5, 3); instead of MyCalculator::add_calc(5, 3);.

Let’s move on to the following section to see more examples.

PHP Static Method Examples

Example 1: Format strings.

class TextFormatter {
    public static function uppercase($text) {
        return strtoupper($text);
    }
}

echo TextFormatter::uppercase("hello"); // Output: HELLO

It shows you a static method that converts a string to uppercase. You do not need to create an object. Just call TextFormatter::uppercase("hello");, and it returns "HELLO".

Example 2: Math helper for multiplication

class MathHelper {
    public static function multiply($a, $b) {
        return $a * $b;
    }
}

echo MathHelper::multiply(4, 5); // Output: 20

This static method multiplies two numbers. It belongs to MathHelper, not any object. You can call MathHelper::multiply(4, 5); anytime, and it returns 20.

Example 3: Track counter without an object.

class Counter {
    private static $count = 0;

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

echo Counter::increment(); // Output: 1
echo Counter::increment(); // Output: 2

This example tracks a count using a static property. The increment() method increases $count each time it runs.

Its value stays the same across multiple calls since $count is static. You do not need an object to keep track of the count.

Wrapping Up

You learned what PHP static methods are and how to use them inside and outside a class. You also saw real examples of static methods.

Here are the key takeaways:

  • A static method belongs to a class, not an object. It is defined using the static keyword and called with ClassName::methodName();.
  • Use static methods when a function does not depend on object properties.
  • Call them without creating an object.
  • Use self::methodName(); to access them within the same class.

FAQ’s

What is a static method in PHP?

A static method belongs to the class itself rather than any instance. This means you can call it without creating an object of the class.

How do I define a static method?

To define a static method, use the static keyword before the function name within a class. For example:
class MyClass {
    public static function myStaticMethod() {
        // method body
    }
}

How can I call a static method?

You can call a static method using the class name followed by the scope resolution operator :: and the method name:
MyClass::myStaticMethod();

When should I use static methods?

Use static methods for functionality that doesn't rely on object properties or instance-specific data. They are suitable for tasks that are common across all instances or don't pertain to object state.

Can static methods access instance properties?

No, static methods cannot access instance properties or the $this keyword because they are not tied to any specific object instance.

Can static methods access static properties?

Yes, static methods can access static properties within the class using the self keyword and the scope resolution operator: for example:
self::$staticProperty;

Similar Reads

PHP filter_input_array: How to Clean and Validate Input

The filter_input_array() filters multiple inputs in PHP at once. It helps you to clean and validate data. Understand the filter_input_array…

PHP array_find: How to Locate Array Values with Examples

PHP array_find was released in PHP 8.4 to locate a value inside an array and returns the first match. Understand…

PHP Elvis Operator: How (?:) Works with Examples

The Elvis operator in PHP is a shorthand version of the ternary operator. PHP allows developers to use this conditional…

How to Connect PHP to MongoDB

Connecting PHP to MongoDB allows you to integrate database functionalities into your web applications. MongoDB is a NoSQL database that…

PHP implode Function: Join Array Values into a String

The implode function in PHP appeared to solve a common need—joining array elements into a single string. It helps format…

PHP $_ENV: Manage Environment Variables

In this tutorial, we will explore a form of superglobal variable in PHP: $_ENV, which symbolizes how PHP reaches for…

PHP Array Operators: Union, Equality, Identity

PHP arrays serve as powerful tools for storing multiple values in a single variable. To manipulate arrays efficiently, PHP provides…

PHP Hello World: Write Your First Program with Code Example

You always start with “Hello World” when you learn a new language. It keeps things simple. You see right away…

PHP fwrite: How to Write Data to Files in PHP

actions, store settings, or even create log files for debugging. That’s where PHP fwrite comes in. It writes data to…

Mastering PHP’s Do-While Loop: Examples and Explanation

The PHP do-while loop is a type of loop that executes a block of code at least once, and then…

Previous Article

PHP OOP Programming: A Complete Tutorial

Next Article

PHP Static Property: How It Works & Examples

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.