Home > database >  PHP: is it possible to callback like in C ?
PHP: is it possible to callback like in C ?

Time:12-02

Im not sure it this is possible in PHP…

I basically want

// A.php

class A {
    public static function foo(int a, string b) {
        //…//
    }
}

to be given to another function in another class. But that other class should not be aware of class A and should not need to include it and instead only specify something like this…

// B.php

class B {
    public static function doSomething(callable $fn) {
        $fn(1,'test'); //<-error
    }
}

Currently I get the error "Class A" not found when I call it with…

include_once('A.php');
include_once('B.php');
B::doSomething('A::foo');

CodePudding user response:

PHP can do callbacks, but I'm not sure if you can do it via classname.

Here's a really simple example:

function Test($mystring) {return "MY STRING = ".$myString;}
function CallMyFunction($functionname,$mydata) 
{
  echo $functionname($mydata);
}

CallMyFunction('Test',"Hello World!");

More info here: https://www.w3schools.com/php/php_callback_functions.asp

CodePudding user response:

The clue was that it seems to do string to function resolvement in the context of the called class, so calling

B::doSomething([A::class, 'foo']);

does it in the context, where A is knewn. At least thats my understanding :D

  • Related