OneBite.Dev - Coding blog in a bite size

Declare A Void Function Without Return Value In PHP

Code snippet for how to Declare A Void Function Without Return Value In PHP with sample and detail explanation

In PHP, functions play a fundamental role in building efficient and effective code. This article details how to declare a void function without a return value in PHP, a functionality which can be incredibly useful in various coding scenarios.

Code snippet

Here is a simple illustration of declaring a void function in PHP:

    function printWelcomeMessage() : void {
        echo "Welcome to our website!";
    }
    
    printWelcomeMessage();

Code Explanation

At first glance, this PHP script may seem quite straightforward. But let’s break it down step by step to ensure absolute clarity.

The declaration of a void function in PHP code starts with the keyword ‘function’, which tells PHP to expect a function declaration.

We then give the function a name - in this case, ‘printWelcomeMessage’. This is followed by empty parentheses. These are used to pass arguments into the function, but in this case, no arguments are needed.

Next, we see ’: void’. This is the return type declaration. The ‘void’ return type was introduced in PHP 7.1. This tells PHP that the function will not return any value.

Within the braces {...} is the block of code that is executed whenever this function is called. Here, we have an ’echo’ statement which will print out “Welcome to our website!“. This function does exactly what the function name suggests - it prints a welcome message.

Lastly, we have the statement ‘printWelcomeMessage();‘. This is how we call or invoke the function we just declared.

Remember that PHP will not execute the function unless it is specifically called in the script. So, if we remove this call, the message will not print to the screen.

In conclusion, declaring a void function without a return value in PHP is pretty straightforward. By using the ‘void’ return type declaration, we communicate clearly to any other developers (and to PHP itself) that this particular function will not be providing any return output.

php