Chapter 3. Simple Callbacks

Of all the differences between PHP and JavaScript, here’s the most difficult: PHP is, at its heart, a sequential language, whereas JavaScript is an event-driven one.

Being sequential or event-driven is essentially an assumption that is built into a language. Languages do not develop in a vacuum. With both PHP and JavaScript, each language was developed in a hurry, with a particular purpose in mind, and deployed to users within months of its creation.

Rasmus Lerdorf invented PHP in 1994 as a replacement for CGI scripts. CGI scripts were usually C (or C++) programs that executed when a browser requested a specific URL and the output from the program was sent back as a web page. These C programs were single threaded and ran from beginning to end in a step-by-step fashion. Lerdorf developed PHP as a substitute. When a browser requested a specific URL, instead of running a C program, the PHP script (page) would be quickly compiled and run, and the output from the script would be sent back as a web page. Since PHP was a drop-in substitute for single-threaded C programs, PHP naturally adopted the single-threaded approach.

Those CGI scripts and early PHP pages really did not have any concept of or need for events. The only two events that might make sense and have any kind of use would be: (1) a URL-invoked event, or (2) a URL invocation completed event. The URL-invoked event was handled by running the PHP script; essentially, the entire PHP script itself was the ...

Get Node.js for PHP Developers now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.