0
0
PHPprogramming~5 mins

Never return type in PHP

Choose your learning style9 modes available
Introduction

The never return type tells PHP that a function will not return any value because it either stops the program or never finishes.

When a function always stops the program, like showing an error and exiting.
When a function runs forever and never ends, like an infinite loop.
When you want to be clear that a function never gives back a result.
Syntax
PHP
function functionName(): never {
    // code that never returns
    exit(); // or throw exception
}

The never type means the function does not return normally.

It helps tools and developers understand the code better.

Examples
This function stops the program and never returns.
PHP
<?php
function stopProgram(): never {
    exit("Stopping now.");
}
This function runs forever and never returns.
PHP
<?php
function infiniteLoop(): never {
    while (true) {
        // runs forever
    }
}
Sample Program

This program shows an error message and stops the program using a function with never return type. The last echo never runs.

PHP
<?php
function stopWithError(string $message): never {
    echo "Error: $message\n";
    exit(1);
}

// Call the function
stopWithError("Something went wrong");

// This line will never run
echo "This will not print.";
OutputSuccess
Important Notes

Functions with never type must not return any value or reach the end normally.

Common ways to never return are exit(), die(), or throwing an exception that is not caught.

Summary

The never return type means the function does not return normally.

Use it for functions that stop the program or run forever.

It helps make your code clearer and safer.