PHP 8: Modern PHP Development · Modern PHP Syntax & Types
Getting Started with PHP 8
Install PHP 8.x, run scripts and a dev server, and enable strict types from day one.
PHP 8 (8.0 in 2020 through 8.4/8.5 today) turned PHP into a modern, strongly typed language with a JIT, union types, enums, attributes, readonly properties and more. Check your version with php -v, list loaded extensions with php -m, and find the active configuration with php --ini.
For local development you can run the built-in web server (php -S localhost:8000 -t public); in production PHP runs behind PHP-FPM with Nginx or Apache. Start every file with declare(strict_types=1); so scalar type declarations are enforced instead of silently coercing values.
<?php
declare(strict_types=1);
function greet(string $name, int $times = 1): string
{
return str_repeat("Hello, {$name}! ", $times);
}
echo greet('Ada', 2), PHP_EOL; // Hello, Ada! Hello, Ada!
// greet('Ada', '2'); // TypeError with strict_types=1
Useful commands
| Command | Purpose |
|---|---|
php -v |
PHP version |
php -m |
Loaded extensions |
php --ini |
Which php.ini files are loaded |
php -S localhost:8000 -t public |
Built-in dev server |
php -l file.php |
Syntax check (lint) |
Common pitfalls
- Forgetting
declare(strict_types=1)— it must be the very first statement and applies per file (to calls made from that file). - Using the built-in server in production; it's single-threaded and meant for development only.
- Editing the wrong php.ini: CLI and FPM often load different files.
Key points
- PHP 8 is a modern, typed language with a JIT
- Enable strict types in every file
- Use the built-in server only for development
Further reading: PHP manual: strict typing
Practice questions
What does declare(strict_types=1) change?
Answer
It makes scalar type declarations strict for calls made from that file: passing '5' to an int parameter throws a TypeError instead of being coerced. It doesn't affect return-value coercion in other files and must be the first statement in the file.
Why might php -i and a web page show different settings?
Answer
The CLI SAPI and PHP-FPM usually load different php.ini files and extensions. Use php --ini for the CLI and phpinfo() (temporarily, never in production) or FPM configuration to check the web SAPI.
Open in the app to mark lessons complete, take notes and track your progress.