PHP Type Declarations
In this page:
Scalar Type Declarations
Adding a type before a function parameter (like function greet(string $name)) makes PHP reject calls with the wrong argument type, catching bugs at the call site instead of deep inside the function body.
Example: Scalar Type Declarations
<?php
function greet(string $name) {
echo "Hello, $name!";
}
greet("Alice");
?>
Login to try C/C++/Java/PHP code in the editor
Return Type Declarations
A return type declared after the parameter list (function getAge(): int) documents and enforces what a function promises to hand back, which helps both readers and static analysis tools trust the function's contract.
Example: Return Type Declarations
<?php
function getAge(): int {
return 30;
}
echo getAge();
?>
Login to try C/C++/Java/PHP code in the editor
Nullable Types
Prefixing a type with a question mark (?string) allows either that type or null, which is essential for parameters or return values that genuinely might have no value, like an optional lookup that can fail to find anything.
Example: Nullable Types
<?php
function findUser(?string $name): ?string {
return $name;
}
var_dump(findUser(null));
?>
Login to try C/C++/Java/PHP code in the editor
Strict Types
declare(strict_types=1) at the top of a file disables PHP's usual implicit type coercion for that file, so passing a string where an int is expected throws a TypeError instead of silently converting.
Example: Strict Types
<?php
declare(strict_types=1);
function double(int $x): int {
return $x * 2;
}
echo double(5);
// double("5") would now throw a TypeError instead of silently converting
?>
Login to try C/C++/Java/PHP code in the editor
Iterable Type
The iterable type accepts either a plain array or any object implementing Traversable, letting a function accept 'anything you can foreach over' without caring which concrete form it takes.
Example: Iterable Type
<?php
function printAll(iterable $items) {
foreach ($items as $item) {
echo $item . "\n";
}
}
printAll([1, 2, 3]);
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 24 topics to unlock
0/24 topics done
Complete these topics first:
- PHP Date & Time
- PHP Math Functions
- PHP JSON Handling
- PHP XML Handling
- PHP cURL Introduction
- PHP REST API Basics
- PHP Composer & Packages
- PHP Autoloading
- PHP Design Patterns
- PHP MVC Architecture
- PHP Security Best Practices
- PHP Performance Optimization
- PHP 8 New Features
- PHP Type Declarations
- PHP Match Expression Advanced
- PHP Fibers
- PHP Attributes
- PHP Magic Constants
- PHP Include & Require
- PHP Iterables
- PHP SimpleXML Parser
- PHP SimpleXML Get
- PHP XML Expat Parser
- PHP DOM Parser