From a script to a tidy middle

A trail through modern PHP. First values, strings and arrays, without which no one else's file makes sense. Then functions, objects and errors. At the end, parsing a request, validating input and building a short response line, as in an ordinary web service.

Foundation

A script, values and a comparison that does not lie.

  1. The script — The file starts with <?php and prints exactly what it promised.
  2. Values — A string, a number and what PHP is willing to convert silently.
  3. Comparison — === does not convert types, == does.

Text and arrays

Strings, lists and maps are three different things.

  1. Strings — Joining, length and reversing without extensions.
  2. Lists — Indexes start at zero; better not to leave gaps.
  3. Maps — A key is a string; a missing key is not an empty string.

Functions

Names, arguments and small closures.

  1. Declaring a function — function returns a value; echo inside it is already a side effect.
  2. Arguments — A default value is a constant, and defaults go at the end.
  3. Closures — A function without a name captures a value through use.

Objects

Fields, visibility and a contract without extra magic.

  1. Fields — An object is assembled by its constructor, not by a scatter of assignments.
  2. Visibility — private hides a field; a method hands out the value.
  3. The contract — An interface says what an object can do, not how it is built.

Errors and types

Exceptions, argument types and null.

  1. Exceptions — throw carries an object; catch catches a specific type.
  2. Scalar types — int in a signature is a promise, not decoration.
  3. The empty value — ?? and ?Type differ: one is about reading, the other about the signature.

The service

A request, a check and a response line.

  1. The query string — Parsing key-value pairs without superglobals.
  2. Checking input — Shape first, then action.
  3. The response line — A code and a short reason, no stack trace.