tmuecksch tmuecksch - 7 months ago 14
PHP Question

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?

Answer

Use a callable:

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

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