Does a simple `return` in a PHP function simply end the function prematurely?

PHP is dynamically typed, so returning no value is equivalent to returning a null value in any type.


function text($var) 

{

    if ( ! $var) {
        return;
    }
    do_something();

}

$var = text('');

echo gettype($var);
echo is_bool($var) ? "true" : "false";
echo is_string($var) ? "true" : "false";
echo is_null($var) ? "true" : "false";

returns:

NULL false false true


Yes, "return;" or return(); in a function stops running that function (or file if the return statement is not in a function) at that point (if the code is executed) and technically returns a null value.

Your first example would output the 'HTTP/1.1 403 Forbidden' header and then end that function if request::is_ajax() equals true.

In your code example:

function text($var) 
{

    if ( ! $var) {
        return;
    }
    do_something();

}
$var = text('');

You can have the following out comes:

  • If $var is NOT TRUE (i.e. false, null, text or an integer), then exit function and return null.
  • If $var is EXACTLY TRUE (the if statement is checking if $var is anything but true), then run do_something();

I would suspect you probably want to change the if statement to either:

if (!is_string($var)) {

if you just want to do_something() to a string or

if (is_null($var)) {

if you only want to do_something() to $var if it's been set. You may also want to change your function declaration to: function text($var==NULL) { so if you call text without a paramter, $var is automatically set to null.


A return with no value returns null.

More information from the manual:

If called from within a function, the return() statement immediately ends execution of the current function, and returns its argument as the value of the function call. return() will also end the execution of an eval() statement or script file.

If called from the global scope, then execution of the current script file is ended. If the current script file was include()ed or require()ed, then control is passed back to the calling file. Furthermore, if the current script file was include()ed, then the value given to return() will be returned as the value of the include() call. If return() is called from within the main script file, then script execution ends. If the current script file was named by the auto_prepend_file or auto_append_file configuration options in php.ini, then that script file's execution is ended.

Tags:

Php

Function