PHP

CALLBACK FUNCTION IN PHP

(a quick example)

WHAT IS A CALLBACK?

01

A function that is passed into another function.

The function then gets called inside the other function.

A callback function can change the way a function acts.

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); } }

THE "MAIN" FUNCTION

02

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

CALLBACK FUNCTIONS

03

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

FETCH CONTENT & SAVE TO FILE fetch("http://site.com", "save");

RUN CALLBACK FUNCTION

04

FETCH CONTENT & OUTPUT IT fetch("http://site.com", "show");