Lesson contents

PHP — Organizing code across files

In PHP, require_once loads a helper file once. Namespaces and a use function declaration let the caller refer to a particular function by its short name.

A simple example

Use a function in a namespace

  1. Start with "abc"
  2. Do this Import and call strlen
  3. Result 3
Inside the Lesson namespace, the use declaration brings the global function name into scope.
lesson.php
<?php
namespace Lesson;
use function strlen;
echo strlen("abc"), PHP_EOL;
Output
3
Advertisements

Share a function between source files

require_once loads the helper from the script directory. The namespace qualifies the function name. The use function declaration makes the short name available in this file.

Room capacity: 8 seats. Already booked: 3 seats. Helper returns: 5 free seats.
Share a room-capacity calculation

A club ticket desk has eight seats and three bookings. Keep the calculation in a helper file so both the booking screen and the check-in screen can use it. With the same inputs, each reports five places left.

Run the example

PHP 8 or later. Run these commands from the directory containing the example.

php lesson.php
boxes.php
<?php
namespace Tutorial\Boxes;

function remaining(int $capacity, int $used): int
{
    return $capacity - $used;
}
lesson.php
<?php
use function Tutorial\Boxes\remaining;

require_once __DIR__ . '/boxes.php';
echo remaining(8, 3), PHP_EOL;
Output
5

Create the files with the names shown and run the command from their common project folder. The entry point gives the helper a capacity of 8 and a used count of 3. The helper returns 5.

Try it yourself

Change the used count from 3 to 8 in the caller.

Check your answer

Running the same command prints 0. No change to the helper is needed.

PHP language reference

Related tags

  • PHP
  • modules
  • source files
  • imports