Using an interactive shell (REPL)

PHP:
Using an interactive shell (REPL)

How to:

Launch the PHP REPL by running php -a in your terminal. Here’s a taste of how it works:

php > echo "Hello, World!";
Hello, World!
php > $arr = [1, 2, 3];
php > print_r($arr);
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)

You can define functions, too:

php > function sum($a, $b) { return $a + $b; }
php > echo sum(5, 10);
15

Deep Dive

REPLs have been around in some form since the early days of LISP in the 1960s. PHP’s interactive shell is less advanced compared to those of languages like Python or JavaScript. It doesn’t persist state between sessions and lacks features like auto-completion. For a more feature-rich PHP REPL, consider alternatives like psysh or boris. These third-party shells offer better introspection tools, tab-completion, and even a debugger.

Under the hood, PHP’s REPL works by compiling and executing each line of code as it’s entered. The limitations of this approach become clear with things like redeclaring classes, which isn’t possible in the same session. It’s great for simple tests but can get cumbersome for complex tasks.

See Also