Type Hinting in PHP allows developers to specify the expected data type of parameters and return values. This improves code reliability, readability, and prevents invalid data from entering functions or methods.
int, float, string, boolarrayint|string?intType hints are placed before parameters, and return types are declared after the method signature using a colon. PHP validates the type at runtime.
// Basic type hinting with parameters and return types
add(5, 10);
echo "
";
echo $calc->greet("Alice");
?>
// Enforcing object types in method parameters
name = $name;
}
}
class UserService {
public function printUser(User $user): void {
echo "User: " . $user->name;
}
}
$user = new User("Bob");
$service = new UserService();
$service->printUser($user);
?>
// Union and nullable type hinting
double(5);
echo "
";
$math->setAge(null);
?>
The output shows how PHP strictly enforces data types and safely handles multiple allowed types or nullable values.
declare(strict_types=1); for strict checkingint parameters and test invalid valuesnull