1

Is it possible to pass a function to another function and then call it? Example:

class TestController extends Controller
{       
    public function sayHello()
    {   
        echo "Hello";
    }

    public function sayBye()
    {   
        echo "Bye";
    }

    public function say($text)
    {
         if ($text === "Hello") {
                 $this->doChecks($text, $this->sayHello);
         }
         else {
                 $this->doChecks($text, $this->sayBye);
         }
    }

    public function doChecks($text, $callback)
    {
         if (is_string($text)) {
                 $callback();
         }
         else {
             echo "ERROR";
         }
    }
}

If you call say() like this say('Hello') then sayHello() should be executed, after the check in doChecks() were passed, otherwise (if $text is not a string) "ERROR" should be printed.

What I get: Undefined property: App\Http\Controllers\TestController::$sayHello

If you call say() like this say('somerandomstuff') then sayBye() should be executed, after the check in doChecks() were passed, otherwise (if $text is not a string) "ERROR" should be printed.

What I get: Undefined property: App\Http\Controllers\TestController::$sayBye


If I try to pass the functions address like this:

 public function doChecks($text, &$callback)

then I get Function name must be a string, if I output $callback with echo inside doChecks like this: echo "'$callback'"; then I get ''

How does it work?

tereško
  • 58,060
  • 25
  • 98
  • 150
Black
  • 18,150
  • 39
  • 158
  • 271
  • I still don't know what I have to change in my code to make it work. – Black Feb 20 '17 at 15:09
  • I was able to solve it by replacing `$this->doChecks($text, $this->sayHello);` with `$this->doChecks($text, array($this, 'sayHello'));` – Black Feb 20 '17 at 18:06
  • And `$this->doChecks($text, $this->sayBye);` with `$this->doChecks($text, array($this, 'sayBye'));` – Black Feb 20 '17 at 18:06

0 Answers0