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.
- You tell == from ===, null from an empty string, a list from a map
- You write functions and classes with visibility, types and exceptions
- You validate input and build a short response line without stray text
Foundation
A script, values and a comparison that does not lie.
- The script — The file starts with <?php and prints exactly what it promised.
- Values — A string, a number and what PHP is willing to convert silently.
- Comparison — === does not convert types, == does.
Text and arrays
Strings, lists and maps are three different things.
- Strings — Joining, length and reversing without extensions.
- Lists — Indexes start at zero; better not to leave gaps.
- Maps — A key is a string; a missing key is not an empty string.
Functions
Names, arguments and small closures.
- Declaring a function — function returns a value; echo inside it is already a side effect.
- Arguments — A default value is a constant, and defaults go at the end.
- Closures — A function without a name captures a value through use.
Objects
Fields, visibility and a contract without extra magic.
- Fields — An object is assembled by its constructor, not by a scatter of assignments.
- Visibility — private hides a field; a method hands out the value.
- The contract — An interface says what an object can do, not how it is built.
Errors and types
Exceptions, argument types and null.
- Exceptions — throw carries an object; catch catches a specific type.
- Scalar types — int in a signature is a promise, not decoration.
- 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.
- The query string — Parsing key-value pairs without superglobals.
- Checking input — Shape first, then action.
- The response line — A code and a short reason, no stack trace.