简体   繁体   中英

How do I execute a callback stored in a static variable of a class in PHP?

I have a simple class with a static callback. But when I try to execute the callback I get the following error:

E_NOTICE : type 8 -- Undefined variable: _fn -- at line 14 Exception: Function name must be a string

Here is my PHP-code:

<?php

class test
{
    public static $_fn = null;

    public static function setFN(callable $fn)
    {
        self::$_fn = $fn;
    }

    public static function do($arg)
    {
        self::$_fn($arg);
    }
}

test::setFN(function ($arg) {
    echo $arg;
});

test::do('test');

?>

Can someone please shed some light, what is wrong here?

You could use call_user_func for calling the stored function:

class test
{
    public static $_fn = null;
    public static function setFN(callable $fn)
    {
        self::$_fn = $fn;
    }
    public static function do($arg)
    {
        call_user_func(self::$_fn, $arg);
    }
}

test::setFN(function ($arg) {
    echo $arg;
});

test::do('test');

Demo: https://3v4l.org/5tHJI

Another workaround is to transfer the callback into a local variable:

public static function do($arg)
{
    $fn = self::$_fn;
    $fn($arg);
}

Demo: https://3v4l.org/7cOaH

Or even shorter:

public static function do($arg)
{
    (self::$_fn)($arg);
}

Demo: https://3v4l.org/OhHfI

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM