← Back to PHP Course | Chapter 8: OOP | Lesson 10 of 14

PHP Static Methods & Properties

What are Static Members?

A static method or property, declared with the static keyword, belongs to the class itself rather than to any individual object, meaning it's shared across every instance and can even be called with no instance at all.

Example: What are Static Members?

php
<?php
class MathHelper {
    static function square($n) {
        return $n * $n;
    }
}
echo MathHelper::square(4);
?>

Static Methods

You call a static method using the class name and :: (scope resolution operator), like MathHelper::square(4), rather than through an object with ->.

Example: Static Methods

php
<?php
class MathHelper {
    static function square($n) {
        return $n * $n;
    }
}
echo MathHelper::square(5);
?>

Static Properties

Static properties retain their value between calls and are shared by all instances of the class, which makes them useful for things like a counter that tracks how many objects of a class have been created so far.

Example: Static Properties

php
<?php
class Counter {
    static $count = 0;
    function __construct() {
        self::$count++;
    }
}
new Counter();
new Counter();
echo Counter::$count;
?>

Static parent Calls

Static methods cannot access $this, since there's no specific object instance they're running on — they can only work with static properties or with parameters passed in explicitly.

Example: Static parent Calls

php
<?php
class Formatter {
    static $prefix = "LOG: ";
    static function format($msg) {
        return self::$prefix . $msg;
    }
}
echo Formatter::format("Started");
?>

When to Use Static

Static members are a good fit for utility functions that don't depend on any particular object's state, like a formatting helper, but overusing static state for things that should vary per-object can make code harder to test.

Example: When to Use Static

php
<?php
class StringHelper {
    static function slugify($text) {
        return strtolower(str_replace(" ", "-", $text));
    }
}
echo StringHelper::slugify("Hello World");
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.