tmuecksch
tmuecksch

Reputation: 6632

Pass a static function of an abstract class as a callback function

Let's say we've implemented a abstract class which holds some tools. For example a mail function:

abstract class Tools {
    public static function sendMail () {
        // do some magic mail sending
    }
}

Now we have an index.php file, which uses the framework Flight for instance (doesn't mind which framework in particular).

In this index.php we define some routes and assign callback functions to be called if a certain route is requested.

Flight::route('POST /mail', Tools::sendMail);

If I try this code PHP returns this exception:

Fatal error: Undefined class constant 'sendMail'

Is there a way to pass a function like this in PHP?

Upvotes: 3

Views: 3195

Answers (3)

user12279300
user12279300

Reputation: 11

You can use this:

[__CLASS__,'MethodName']

if the callback is made in the same class or

[Class::class,'MethodName']

if it is not.

Upvotes: 1

Markus Malkusch
Markus Malkusch

Reputation: 7868

Use a callable:

public static function route($method, callable $callable)
{
    $callable();
}

Flight::route('POST /mail', function () { Tools::sendMail(); });

Upvotes: 3

Gershom Maes
Gershom Maes

Reputation: 8140

You'll need to pass 2 things in order to reference a static class method: The name of the class, and the name of the static function to call

//define the method
function callStaticClassMethod($className, $funcName) {
    $className::$funcName();
}

//call the method
callStaticClassMethod('Tools', 'sendMail');

I'm not aware of any other way to directly reference a static function.

Upvotes: 0

Related Questions