PHP type hinting lets you declare the expected type of a value in function parameters, return values, class properties, and more. It helps PHP catch wrong values early instead of allowing small mistakes to move deeper into the application.
For example, if a function expects an integer, you can declare it as int. If another developer passes an array or object by mistake, PHP can throw a clear TypeError.
In modern PHP, this feature is officially called type declarations. But many developers still search for it as type hinting, so this article uses both terms naturally.
Quick Answer: What is PHP Type Hinting?
PHP type hinting is the practice of adding type declarations to your code. You can use it to define what type a function argument should receive, what type a function should return, and what type a class property should hold.
<?php
declare(strict_types=1);
function calculateTotal(float $price, int $quantity): float
{
return $price * $quantity;
}
echo calculateTotal(25.50, 2);
In this example, $price must be a float, $quantity must be an integer, and the function must return a float.
Why Type Hinting is Useful in PHP
PHP is a flexible language. That is useful, but it can also hide mistakes. Type hinting gives your code a clear contract.
When a function says it accepts an int, other developers can understand the expected input without reading the full function body. This makes the code easier to maintain.
Type hinting also helps you catch bugs earlier. Instead of getting an unexpected result later, PHP can stop the script with a clear error when the wrong type is passed.
It is especially useful in larger applications where data moves through many functions, classes, and service layers.
- It makes function inputs and outputs clear.
- It improves code readability.
- It helps catch wrong values early.
- It works well with IDE autocomplete and static analysis tools.
- It makes refactoring safer.
PHP Type Hinting Supported Types
PHP has expanded type declarations significantly over the years. Modern PHP supports scalar types, class types, interfaces, arrays, callable values, nullable types, union types, intersection types, and more.
The following are the most commonly used type declarations in day-to-day PHP development.
| Type | Description | Example |
|---|---|---|
int |
Integer numbers | function add(int $a) |
float |
Floating-point numbers | function discount(float $price) |
string |
Text values | function greet(string $name) |
bool |
Boolean values | function isActive(bool $status) |
array |
Arrays | function process(array $items) |
object |
Any object | function save(object $model) |
callable |
Functions, closures, or callable methods | function execute(callable $callback) |
iterable |
Arrays or Traversable objects | function display(iterable $rows) |
mixed |
Any value | function logValue(mixed $value) |
Class |
A specific class or object | function save(User $user) |
Interface |
An object implementing an interface | function cache(CacheInterface $cache) |
Besides these basic types, PHP also supports nullable types (?string), union types (int|string), intersection types, and literal types such as true and false in recent PHP versions. We’ll cover the most practical ones next.
Type Hinting Function Parameters
The most common use of type hinting is for function parameters. It tells PHP what type of value a function expects.
If the caller passes a value of the wrong type, PHP throws a TypeError. This makes bugs easier to find during development.
<?php
declare(strict_types=1);
function calculateArea(float $length, float $width): float
{
return $length * $width;
}
echo calculateArea(12.5, 8);
Output
100
If you accidentally pass a string instead of a number, PHP reports the problem immediately.
<?php
declare(strict_types=1);
function calculateArea(float $length, float $width): float
{
return $length * $width;
}
echo calculateArea("twelve", 8);
Output
Fatal error:
Uncaught TypeError:
calculateArea(): Argument #1 ($length) must be of type float, string given
This is much better than allowing an invalid value to continue through the application and fail later in a less obvious place.
Using Class Type Hinting
You can also require a function to receive an object of a specific class.
<?php
class User
{
public string $name;
public function __construct(string $name)
{
$this->name = $name;
}
}
function welcome(User $user): void
{
echo "Welcome, {$user->name}";
}
$user = new User("John");
welcome($user);
This guarantees that the welcome() function always receives a User object.
PHP Return Type Declarations
Type hinting is not limited to function parameters. You can also declare the type that a function must return.
This ensures that every execution path returns the expected data type. If not, PHP throws a TypeError.
<?php
declare(strict_types=1);
function getFullName(string $firstName, string $lastName): string
{
return $firstName . " " . $lastName;
}
echo getFullName("John", "Doe");
Output
John Doe
If the function returns the wrong type, PHP reports the error immediately.
<?php
declare(strict_types=1);
function getAge(): int
{
return "25";
}
echo getAge();
Output
Fatal error:
Uncaught TypeError:
getAge(): Return value must be of type int, string returned
Using void Return Type
Some functions perform an action but do not return a value. In such cases, use the void return type.
<?php
function writeLog(string $message): void
{
echo "Log: " . $message;
}
writeLog("Application started");
A function declared as void must not return a value.
Using Nullable Return Types
Sometimes a function may return either a value or null. You can express this using a nullable type.
<?php
function findUser(int $id): ?string
{
$users = [
1 => "John",
2 => "Alice"
];
return $users[$id] ?? null;
}
echo findUser(1);
The ? before the type means the function may return either the specified type or null.
Union Types
Before PHP 8.0, a parameter or return value could have only one declared type. If a function needed to accept more than one type, developers often skipped type declarations altogether or used PHPDoc comments.
PHP 8.0 introduced union types. They allow you to specify multiple accepted types using the | operator.
<?php
function formatValue(int|string $value): string
{
return "Value: " . $value;
}
echo formatValue(100);
echo "<br>";
echo formatValue("A100");
Output
Value: 100
Value: A100
This is useful when a value can legitimately have more than one type. For example, an order ID may be stored as either an integer or a string depending on the data source.
Combining Union and Nullable Types
You can also include null as one of the allowed types.
<?php
function findProduct(int|string|null $id): ?string
{
if ($id === null) {
return null;
}
return "Product #" . $id;
}
echo findProduct(25);
Although ?string is a shortcut for string|null, you cannot mix the shortcut with additional types. For example, this is invalid:
?int|string
Instead, write the complete union type.
int|string|null
Using the explicit form keeps the declaration valid and easier to understand.
Strict Types
By default, PHP performs type coercion for scalar values. For example, if a function expects an integer, PHP may automatically convert a numeric string into an integer.
If you want PHP to enforce exact types, enable strict mode by placing the following statement at the beginning of the file.
<?php
declare(strict_types=1);
Consider this example.
<?php
declare(strict_types=1);
function square(int $number): int
{
return $number * $number;
}
echo square("5");
Output
Fatal error:
Uncaught TypeError:
square(): Argument #1 ($number) must be of type int, string given
Without strict_types=1, PHP would automatically convert the string "5" to the integer 5.
Many modern PHP projects enable strict types because they make bugs easier to detect during development and reduce unexpected type conversions.
Typed Properties
Since PHP 7.4, you can declare types for class properties. This helps ensure that an object always stores values of the expected type.
Without typed properties, a property can accidentally receive any value. With a declared type, PHP validates every assignment.
<?php
class Product
{
public string $name;
public float $price;
public int $stock;
}
$product = new Product();
$product->name = "Wireless Mouse";
$product->price = 799.50;
$product->stock = 25;
echo $product->name;
If you assign an incompatible value, PHP throws a TypeError.
<?php
class Product
{
public float $price;
}
$product = new Product();
$product->price = "799";
When strict_types=1 is enabled, assigning a string to a float property results in an error.
Nullable Properties
If a property may not always have a value, prefix the type with ?.
<?php
class Customer
{
public ?string $phone = null;
}
$customer = new Customer();
var_dump($customer->phone);
This allows the property to hold either a string or null.
Common Type Hinting Errors
Most type-related errors are easy to fix once you understand why they occur. Here are some common situations.
Passing the Wrong Argument Type
The function expects one type but receives another.
<?php
function add(int $a, int $b): int
{
return $a + $b;
}
add([], 10);
Fix: Pass an integer instead of an array.
Returning the Wrong Type
The declared return type must match the value returned by the function.
<?php
function getStatus(): bool
{
return "success";
}
Fix: Return true or false, or change the declared return type if a string is intended.
Forgetting to Handle null
If a variable can be null, declare it as a nullable type.
<?php
function getEmail(): ?string
{
return null;
}
Using nullable types makes your intent clear and avoids unexpected type errors.
Handling TypeError Exceptions
When a value does not match the declared type, PHP throws a TypeError. In production applications, you can catch this exception to log the error or display a user-friendly message instead of letting the application terminate.
<?php
declare(strict_types=1);
function calculateArea(float $length, float $width): float
{
return $length * $width;
}
try {
echo calculateArea("ten", 5);
} catch (TypeError $e) {
echo "Error: " . $e->getMessage();
}
Output
Error: calculateArea(): Argument #1 ($length) must be of type float, string given
Catching TypeError is useful when you want to log errors, return a JSON response from an API, or show a friendly message to the user instead of exposing a fatal error.
Best Practices for PHP Type Hinting
Type hinting is most effective when it is used consistently across your project. The following practices can help you write cleaner and more reliable PHP code.

Use the Most Specific Type Possible
Avoid using mixed or object unless a function genuinely accepts different kinds of values. More specific types make the code easier to understand.
// Good
function sendEmail(string $email): void
// Less descriptive
function sendEmail(mixed $email): void
Enable Strict Types in New Projects
Adding declare(strict_types=1); at the top of your PHP files helps catch invalid data early and prevents unexpected type conversions.
Declare Return Types
Don’t stop with parameter types. Return type declarations make it clear what a function produces and reduce bugs during refactoring.
function calculateTax(float $amount): float
{
return $amount * 0.18;
}
Prefer Interfaces Over Concrete Classes
When working with object-oriented code, type hint an interface whenever possible. This keeps your code flexible and easier to test.
function store(CacheInterface $cache): void
{
// ...
}
Avoid Unnecessary Union Types
Union types are useful, but using too many of them can make a function harder to understand. If a function accepts several unrelated types, it may be doing more than one job.
Keep Type Declarations Up to Date
As your application evolves, review your type declarations. Remove overly broad types and replace them with more accurate ones whenever possible.
Frequently Asked Questions
What is the difference between type hinting and type declarations?
They refer to the same concept. Modern PHP documentation uses the term type declarations, while many developers still use the older term type hinting.
Does PHP support scalar type hinting?
Yes. Modern PHP supports scalar types such as int, float, string, and bool for parameters, return values, and properties.
Should I always enable strict_types=1?
For new applications, it is generally recommended. It makes type checking more predictable and helps detect programming mistakes earlier.
Can I use multiple types for one parameter?
Yes. PHP 8 introduced union types, allowing declarations such as int|string or string|null.
Is type hinting mandatory in PHP?
No. PHP remains a dynamically typed language, so type declarations are optional. However, using them consistently improves readability, reduces bugs, and makes large applications easier to maintain.
Conclusion
PHP type hinting is one of the simplest ways to make your code more reliable. By declaring the expected types for parameters, return values, and class properties, you create clear contracts that are easier to understand and maintain.
Modern PHP offers powerful features such as typed properties, nullable types, union types, and strict type checking. Using these features consistently helps you catch mistakes early and write production-ready applications.
If you’re learning modern PHP, make type declarations a regular part of your coding style. Your future self and anyone who works with your code will appreciate the added clarity.
If you’d like to explore more modern PHP features, you may also find these tutorials useful:
Download the Example Project
This tutorial includes a complete example project demonstrating the different types of PHP type declarations discussed in this article.
The project contains examples for:
- Parameter type declarations
- Return type declarations
- Typed properties
- Nullable types
- Union types
- Strict types
- Handling
TypeErrorexceptions
Thanks, great explanation.
Welcome Vas.