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
- Start with "abc"
- Do this Import and call strlen
- Result 3
<?php
namespace Lesson;
use function strlen;
echo strlen("abc"), PHP_EOL;
3
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.
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
<?php
namespace Tutorial\Boxes;
function remaining(int $capacity, int $used): int
{
return $capacity - $used;
}
<?php
use function Tutorial\Boxes\remaining;
require_once __DIR__ . '/boxes.php';
echo remaining(8, 3), PHP_EOL;
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.