PHP Static Methods

Ma Mahalakshmi V Updated 14 Nov 2026
6 min read ·Lesson 166 of 255

What Is a Static Method?

In simple terms: A static method belongs to the class itself, not to any particular object. You call it directly on the class name, without creating an object first: Str::slug('Hello World'). It is useful for operations that do not need any object's data — like converting text or creating objects in different ways.

Technically: A method declared with the static keyword is called with the scope resolution operator: ClassName::method(). Inside a static method there is no $this; it can access only its parameters, static properties, constants, and other static methods (through self:: or static::). Static methods can still create and return objects.

Instance Methods vs Static Methods

Instance MethodStatic Method
Declared aspublic function total()public static function fromArray()
Called as$cart->total()Money::fromRupees(10)
Needs an objectYesNo
$this availableYesNo
Typical useBehavior using the object's stateFactories, pure helpers, class-level operations

Defining and Calling Static Methods

<?php
final class Str
{
    public static function slug(string $text): string
    {
        return strtolower(trim(preg_replace('/[^A-Za-z0-9]+/', '-', $text), '-'));
    }

    public static function limit(string $text, int $length, string $end = '...'): string
    {
        if (mb_strlen($text) <= $length) {
            return $text;
        }

        return rtrim(mb_substr($text, 0, $length)) . $end;
    }

    public static function headline(string $text): string
    {
        return self::limit(ucwords(strtolower($text)), 25);
    }
}

echo Str::slug('Learn PHP OOP!') . "\n";
echo Str::limit('Learn PHP object-oriented programming', 20) . "\n";
echo Str::headline('LEARN PHP OBJECT-ORIENTED PROGRAMMING') . "\n";

print_r(array_map(Str::slug(...), ['Desk Lamp', 'Gel Pen (Blue)']));

Output

learn-php-oop
Learn PHP object-ori...
Learn Php Object-oriented...
Array
(
    [0] => desk-lamp
    [1] => gel-pen-blue
)

How It Works

  1. Str::slug(...) is called on the class; no new Str() is needed.
  2. Inside the class, one static method calls another with self::limit(...).
  3. These methods depend only on their parameters — they are pure functions grouped in a class.
  4. Str::slug(...) (first-class callable syntax) turns the static method into a callback for array_map(); the older forms [Str::class, 'slug'] and 'Str::slug' also work.

Note how ucwords() produced Php and Object-oriented: it capitalizes only after spaces by default, and it does not know about acronyms. Static helpers are only as smart as their implementation.


Named Constructors

The most valuable use of static methods in OOP is creating objects in clearly named ways (see PHP Constructor):

<?php
final class Temperature
{
    private function __construct(private float $celsius) {}

    public static function fromCelsius(float $celsius): self
    {
        return new self($celsius);
    }

    public static function fromFahrenheit(float $fahrenheit): self
    {
        return new self(($fahrenheit - 32) * 5 / 9);
    }

    public function celsius(): float
    {
        return round($this->celsius, 1);
    }
}

echo Temperature::fromFahrenheit(98.6)->celsius() . " °C\n";
echo Temperature::fromCelsius(36.6)->celsius() . " °C\n";

Output

37 °C
36.6 °C

The static methods have full access to the class's private constructor, while outside code cannot call it. The names make it impossible to confuse Celsius and Fahrenheit input.


$this Is Not Available

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

    public static function reset(): void
    {
        $this->count = 0;
    }
}

try {
    Counter::reset();
} catch (Error $e) {
    echo $e->getMessage() . "\n";
}

Output

Using $this when not in object context

A static method is not called on an object, so there is no object whose count could be reset. Methods that work with an object's state must be instance methods.

Calling Instance Methods Statically

The reverse is also an error:

<?php
class Cart
{
    public function total(): float
    {
        return 0.0;
    }
}

try {
    Cart::total();
} catch (Error $e) {
    echo $e->getMessage() . "\n";
}

Output

Non-static method Cart::total() cannot be called statically

Calling Static Methods on Objects

Static methods can also be called through an object ($str::slug('x') or $object->staticMethod()), but this hides the fact that no object state is used. Prefer ClassName::method().


self:: vs static::

Inside a class, static methods are called with self:: or static:::

  • self::method() calls the method of the class where the code is written.
  • static::method() calls the method of the class that was actually called, which matters when a child class overrides the static method.

This difference, called late static binding, is explained in Late Static Binding.


When Static Methods Are a Good Choice

Good UseExample
Named constructors / factoriesMoney::fromPaise(500), User::fromArray($row)
Pure helper functions grouped by topicStr::slug(), Arr::pluck()
Operations on the class as a wholeOrder::statuses() returning all valid statuses
Enum-like lookupsPaymentMethod::fromCode('upi')

When to Avoid Them

ProblemWhy
Hidden dependenciesMailer::send() called deep inside a class cannot be replaced in tests
Global stateStatic methods that change static properties behave like global variables
InflexibilityStatic calls cannot be swapped for another implementation via interfaces
// Hard to test: a fixed, static dependency
final class OrderService
{
    public function place(array $order): void
    {
        Mailer::send($order['email'], 'Order placed');
    }
}

// Flexible: the dependency is injected and can be replaced
final class OrderService
{
    public function __construct(private MailerInterface $mailer) {}

    public function place(array $order): void
    {
        $this->mailer->send($order['email'], 'Order placed');
    }
}

Static methods are ideal for code with no side effects and no dependencies. Anything that talks to databases, files, networks, or the clock is better provided as an injected object.

Note: Laravel "facades" (Cache::get(), Mail::send()) look like static calls but forward to objects resolved from a service container, which is how they remain replaceable in tests.


Practical Example: Building Objects From Database Rows

<?php
final class Customer
{
    public function __construct(
        public readonly int $id,
        public readonly string $name,
        public readonly string $email,
        public readonly DateTimeImmutable $joinedAt,
    ) {}

    public static function fromRow(array $row): self
    {
        return new self(
            (int) $row['id'],
            $row['name'],
            strtolower($row['email']),
            new DateTimeImmutable($row['joined_at']),
        );
    }

    public static function fromRows(array $rows): array
    {
        return array_map(self::fromRow(...), $rows);
    }
}

$rows = [
    ['id' => '7', 'name' => 'Asha', 'email' => 'Asha@Example.com', 'joined_at' => '2026-01-12 09:30:00'],
    ['id' => '9', 'name' => 'Bala', 'email' => 'bala@example.com', 'joined_at' => '2026-03-05 18:10:00'],
];

foreach (Customer::fromRows($rows) as $customer) {
    printf("#%d %s <%s> joined %s\n", $customer->id, $customer->name, $customer->email, $customer->joinedAt->format('M Y'));
}

Output

#7 Asha <asha@example.com> joined Jan 2026
#9 Bala <bala@example.com> joined Mar 2026

Step-by-Step Explanation

  1. Database drivers return rows as arrays of strings. fromRow() converts one row into a properly typed Customer: the ID becomes an int, the email is normalized, and the date becomes a DateTimeImmutable.
  2. fromRows() maps every row with self::fromRow(...).
  3. The conversion logic lives in the class it belongs to, and every part of the application creates customers from rows the same way.

Common Mistakes

Using $this in Static Methods

Effect: Error: Using $this when not in object context.

Fix: Pass the needed data as parameters, or make the method non-static.

Calling Instance Methods Statically

Effect: Error: Non-static method ... cannot be called statically.

Fix: Create an object and call the method on it.

Static Methods With Side Effects Everywhere

Effect: Hidden dependencies, global state, and untestable code.

Fix: Inject services as objects; keep static methods pure.

"Utility" Classes Collecting Unrelated Functions

Effect: A Helpers class with dozens of unrelated methods.

Fix: Group helpers by topic (Str, Arr, Money), or use namespaced functions.


Best Practices

  • Use static methods for named constructors and pure, dependency-free helpers.
  • Keep side effects (database, files, network, time) in injected objects, not static calls.
  • Call static methods with ClassName::method(), and use static:: when subclasses may override them.
  • Use first-class callable syntax (ClassName::method(...)) to pass static methods as callbacks.
  • Avoid static methods that read or change static state unless that state is intentional and well-contained.

Official reference: https://www.php.net/manual/en/language.oop5.static.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Home PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions Modify Strings Concatenate Strings Slicing Strings Escape Characters String Interpolation Heredoc and Nowdoc Search in Strings Multibyte Strings PHP Floats PHP Casting PHP Type Juggling PHP Math PHP Random Numbers PHP Constants PHP Magic Constants PHP Operators Arithmetic Operators Assignment Operators Comparison Operators Increment / Decrement Operators Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence PHP If...Else...Elseif PHP If PHP If Operators PHP If...Else PHP Shorthand if PHP Nested if PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement Continue Statement PHP Functions User-defined Functions Function Arguments Default Argument Values Pass by Reference Named Arguments Variadic Functions Return Values Type Declarations in Functions Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS $_SERVER $_REQUEST $_POST $_GET $_FILES $_COOKIE $_SESSION \$\_ENV PHP RegEx RegEx Patterns RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions PHP Form Handling PHP Form Validation PHP Form Required PHP Form URL/E-mail Form Input Sanitizing Escaping Output (htmlspecialchars) Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting DateTime Class Timezones PHP Include Include vs Require PHP File Handling PHP File Open/Read PHP File Create/Write File Delete / Rename / Copy PHP Directories PHP CSV Files PHP File Upload PHP Cookies PHP Sessions PHP Filters PHP Filters Advanced PHP Callback Functions PHP JSON PHP Exceptions Error Handling Custom Error Handler Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators PHP What is OOP PHP Classes/Objects The $this Keyword PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Destructor PHP Access Modifiers Readonly Properties PHP Inheritance Method Overriding The final Keyword PHP Class Constants PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning Comparing Objects Anonymous Classes PHP Enums PHP Namespaces Autoloading Classes PHP Iterables Iterators Object Serialization Strict Types Union Types Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data MySQL Joins with PHP Pagination with PHP PDO Introduction PDO Connect PDO Prepared Statements PDO Fetch Modes PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention CSRF Protection Session Security Secure Cookies File Upload Security Filesystem Security Error Reporting in Production Hiding PHP Encryption with Sodium PHP Configuration (php.ini) PHP Command Line (CLI) Composer PSR-4 Autoloading Installing Extensions (PECL / PIE) Debugging PHP OPcache & Performance Garbage Collection PHP-FPM Migrating to PHP 8 Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Image Upload Gallery Project: Shopping Cart with Sessions Project: Simple Blog Project: REST API with PHP
Ask about this post
AI Ask about this post

Ask questions about PHP Static Methods and get answers drawn from it.

Signed-in readers only.