How to call a static method in PHP when you have the class name in a variable

Wrap the variable (that holds the class name) in brackets:

<?php

class A
{
    public static function foo($arg)
    {
        return 'Argument was "' . $arg . '"' . PHP_EOL;
    }
}

$result = A::foo('triggered via named class');
echo $result;

$className = A::class;
$result = ($className)::foo('trigged via variable');
echo $result;

The output of the above code:

php a.php
Argument was "triggered via named class"
Argument was "trigged via variable"

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.