0
0
PHPprogramming~5 mins

Static properties and methods in PHP

Choose your learning style9 modes available
Introduction

Static properties and methods belong to the class itself, not to any specific object. This means you can use them without creating an object first.

When you want to keep a value shared by all objects of a class, like a counter.
When you need a utility function that doesn't depend on object data.
When you want to store configuration or constants related to the class.
When you want to track how many objects of a class have been created.
When you want to call a method without creating an object first.
Syntax
PHP
<?php
class ClassName {
    public static $propertyName = 'value';

    public static function methodName() {
        // code here
    }
}

// Access static property
ClassName::$propertyName;

// Call static method
ClassName::methodName();
?>

Use static keyword to declare static properties and methods.

Access static members with :: operator, not with ->.

Examples
This example shows a static property $count and a static method increment() that increases the count.
PHP
<?php
class Counter {
    public static $count = 0;

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

Counter::increment();
echo Counter::$count; // prints 1
?>
This example shows a static method that calculates the square of a number without needing an object.
PHP
<?php
class MathHelper {
    public static function square($num) {
        return $num * $num;
    }
}

echo MathHelper::square(4); // prints 16
?>
Sample Program

This program counts how many Book objects are created using a static property and method.

PHP
<?php
class Book {
    public static $totalBooks = 0;
    public $title;

    public function __construct($title) {
        $this->title = $title;
        self::$totalBooks++;
    }

    public static function getTotalBooks() {
        return self::$totalBooks;
    }
}

$book1 = new Book("PHP Basics");
$book2 = new Book("Learn PHP");

echo "Total books created: " . Book::getTotalBooks();
?>
OutputSuccess
Important Notes

Inside the class, use self:: to access static properties or methods.

Static properties keep their value shared across all objects of the class.

You cannot use $this inside static methods because there is no object context.

Summary

Static properties and methods belong to the class, not objects.

Use :: to access static members.

They are useful for shared data or utility functions.