PHP

CALLBACK FUNCTION - SIMPLE EXAMPLES

WHAT IS A CALLBACK?

01

1) A function that is passed into another function.

2) The function then gets called inside the other function.

WE WILL PASS FUNKYFN() INTO CALL_USER_FUNC() function funkyFn () { echo "YO!"; }

VERY SIMPLE CALLBACK

02

CALL_USER_FUNC() CALLS BACK TO FUNKYFN() call_user_func("funkyFn");

"MAIN" FUNCTION function fetch ($url, $after) {   FETCH CONTENT FROM URL   $ch = curl_init();   curl_setopt($ch, CURLOPT_URL, $url);   curl_setopt($ch, CURLOPT_   RETURNTRANSFER, true);   $result = curl_exec($ch);     CALLBACK AFTER FETCH   if (is_callable($after)) { $after($result); } }

PRACTICAL EXAMPLE (A)

03

CALLBACK - SAVE TO FILE function save ($data) {   file_put_contents("demo.html", data);  }

PRACTICAL EXAMPLE (B)

04

CALLBACK - DIRECT OUTPUT function show ($data) { echo $data; }

THIS WILL SAVE THE FETCH fetch("http://site.com", "save");

PRACTICAL EXAMPLE (C)

05

BUT THIS WILL DIRECTLY SHOW IT fetch("http://site.com", "show");