Php Oops Static Methods
php Object-Oriented Programming (OOP) static methods with example
Accessing Static Methods:
Defining Static Methods
class MyClass {
public static function myStaticMethod() {
return "Hello, World!";
}
}
Calling Static Methods
echo MyClass::myStaticMethod();
Static Properties
class Math {
public static $pi = 3.14159;
public static function circleArea($radius) {
return self::$pi * $radius * $radius;
}
}
echo Math::circleArea(5);
Output:
78.53975
Inheritance and Static Methods
class ParentClass {
public static function staticMethod() {
return "Static method from Parent Class";
}
}
class ChildClass extends ParentClass {}
echo ChildClass::staticMethod();
Output:
Static method from Parent Class
Static Bindings
class BaseClass {
public static function who() {
return __CLASS__;
}
public static function test() {
return static::who();
}
}
class DerivedClass extends BaseClass {
public static function who() {
return __CLASS__;
}
}
echo BaseClass::test();
echo DerivedClass::test();
PHP 5.3 introduced late static bindings.
Singleton Pattern
class Singleton {
private static $instance = null;
private function __construct() {
// Private constructor to prevent multiple instances
}
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
}
$instance1 = Singleton::getInstance();
$instance2 = Singleton::getInstance();
var_dump($instance1 === $instance2);
Output:
bool(true)
Example
<?php
class MathOperations {
// Static method to add two numbers
public static function add($a, $b) {
return $a + $b;
}
// Static method to subtract two numbers
public static function subtract($a, $b) {
return $a - $b;
}
// Static method to multiply two numbers
public static function multiply($a, $b) {
return $a * $b;
}
// Static method to divide two numbers
public static function divide($a, $b) {
if ($b == 0) {
return "Cannot divide by zero";
}
return $a / $b;
}
}
// Calling static methods without creating an instance of the class
echo MathOperations::add(10, 5);
echo MathOperations::subtract(10, 5);
echo MathOperations::multiply(10, 5);
echo MathOperations::divide(10, 5);
echo MathOperations::divide(10, 0);
?>