Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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?

like image 477
tmuecksch Avatar asked Nov 26 '25 20:11

tmuecksch


2 Answers

Use a callable:

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

Flight::route('POST /mail', function () { Tools::sendMail(); });
like image 173
Markus Malkusch Avatar answered Nov 28 '25 17:11

Markus Malkusch


You can use this:

[__CLASS__,'MethodName']

if the callback is made in the same class or

[Class::class,'MethodName']

if it is not.

like image 27
user12279300 Avatar answered Nov 28 '25 15:11

user12279300