</>
Skip to content
PHP lessons (40/49)

PHP — Static Methods

static keyword

<?php
class Person {
    public static function create(): static {
        return new static();
    }

    public function getClass(): string {
        return static::class;
    }
}

class Employee extends Person {}

$p = new Person();
$e = new Employee();

echo $p->getClass(); // Person
echo $e->getClass(); // Employee
?>

Factory pattern

<?php
abstract class Animal {
    abstract public function speak(): string;

    public static function create(string $type): static {
        return match($type) {
            'dog' => new Dog(),
            'cat' => new Cat(),
            default => throw new InvalidArgumentException("Unknown type: $type"),
        };
    }
}

class Dog extends Animal {
    public function speak(): string { return 'Woof!'; }
}

class Cat extends Animal {
    public function speak(): string { return 'Meow!'; }
}

$animal = Animal::create('dog');
echo $animal->speak(); // Woof!
?>

Mini Practice

Write PHP code that:

  1. Uses static::class to get the current class name
  2. Creates a factory method with static binding
  3. Demonstrates late vs early static binding

Up Next

In the next lesson, you'll learn about Final Keyword — preventing inheritance.

Related Topics

Frequently Asked Questions about Static Methods

What is Static Methods in PHP?

Static Methods is a fundamental concept in PHP. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Static Methods?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Static Methods.

Why is Static Methods important in PHP?

Static Methods is essential for PHP development. Understanding this concept will help you write better code and solve real-world problems more effectively.