tmuecksch tmuecksch - 2 years ago 125
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 Source

Use a callable:

public static function route($method, callable $callable)

Flight::route('POST /mail', function () { Tools::sendMail(); });
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download