Passing static methods as arguments in PHP

In PHP, you can pass static methods as arguments to functions using the same syntax employed by is_callable() and call_user_func(). This allows for flexible method calling and dynamic programming patterns.

Syntax

Static methods can be passed using several formats −

// Array format: [ClassName, 'methodName']
// String format: 'ClassName::methodName'

Example with Static Method

Here's how to pass and call a static method as an argument −

<?php
class MyClass {
    public static function sayHello() {
        return "Hello from static method!";
    }
    
    public static function calculate($a, $b) {
        return $a + $b;
    }
}

// Method 1: Using array format
$static_method = [MyClass::class, 'sayHello'];
var_dump(is_callable($static_method));
echo call_user_func($static_method);

echo "<br>";

// Method 2: Using string format
$calc_method = 'MyClass::calculate';
var_dump(is_callable($calc_method));
echo call_user_func($calc_method, 10, 5);
?>
bool(true)
Hello from static method!
bool(true)
15

Passing to Custom Functions

You can create functions that accept static methods as parameters −

<?php
class Calculator {
    public static function add($x, $y) {
        return $x + $y;
    }
    
    public static function multiply($x, $y) {
        return $x * $y;
    }
}

function executeOperation($callback, $num1, $num2) {
    if (is_callable($callback)) {
        return call_user_func($callback, $num1, $num2);
    }
    return "Invalid callback";
}

// Pass static methods as arguments
$result1 = executeOperation(['Calculator', 'add'], 8, 3);
$result2 = executeOperation('Calculator::multiply', 4, 7);

echo "Addition: " . $result1 . "<br>";
echo "Multiplication: " . $result2;
?>
Addition: 11
Multiplication: 28

Conclusion

Static methods can be passed as arguments using array format ['Class', 'method'] or string format 'Class::method'. Always validate with is_callable() before execution to ensure the method exists and is accessible.

Updated on: 2026-03-15T08:44:12+05:30

845 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements