×

php · level 2 · unit 7 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Small typed functions turn a script into an app.

Most web apps do the same few jobs again and again: read the request, validate it, save to the database, then show the results safely. Give each job its own small function with types, and the main part of your program reads like a to-do list.

Moving code into functions like this, without changing what it does, is called refactoring. Each function can be tested on its own, and a bad value meets a clear exception instead of a mystery.

A function can take the database object as an argument too. Its type declaration is PDO, the name of that kind of object.

<?php
function clean_title(array $form): string {
    $title = trim($form["title"] ?? "");
    if ($title === "") { throw new InvalidArgumentException("A task needs a title"); }
    return $title;
}
function show_task(array $row): string {
    return sprintf("#%d %s", $row["id"], htmlspecialchars($row["title"]));
}
$_POST = ["title" => " Buy <b>milk</b> "];
$task = ["id" => 1, "title" => clean_title($_POST)];
echo show_task($task) . "\n";

Good function names, like clean_title and show_task, explain the program before anyone reads the insides.