what does a php function return by default?

PhpFunctionVariablesLanguage Design

Php Problem Overview


If I return nothing explicitly, what does a php function exactly return?

function foo() {}
  1. What type is it?

  2. What value is it?

  3. How do I test for it exactly with === ?

  4. Did this change from php4 to php5?

  5. Is there a difference between function foo() {} and function foo() { return; }

(I am not asking how to test it like if (foo() !=0) ...)

Php Solutions


Solution 1 - Php

  1. null
  2. null
  3. if(foo() === null)
  4. Nope.

You can try it out by doing:

$x = foo();
var_dump($x);

Solution 2 - Php

Not returning a value from a PHP function has the same semantics as a function which returns null.

function foo() {}

$x=foo();

echo gettype($x)."\n";
echo isset($x)?"true\n":"false\n";
echo is_null($x)?"true\n":"false\n";

This will output

NULL
false
true

You get the same result if foo is replaced with

function foo() {return null;}

There has been no change in this behaviour from php4 to php5 to php7 (I just tested to be sure!)

Solution 3 - Php

I did find an oddity when specifying function return types. When you do, you must be explicit about returning something from your functions.

<?php

function errorNoReturnDeclared($a = 10) : ?string {
    if($a == 10) {
        echo 'Hello World!';
    }
}

errorNoReturnDeclared(); //Fatal error

Error:

 Uncaught TypeError: Return value of errorNoReturnDeclared() must be of the type string or null, none returned in 

So if you decide to add some return type specifications on old functions make sure you think about that.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser89021View Question on Stackoverflow
Solution 1 - PhpPatrikAkerstrandView Answer on Stackoverflow
Solution 2 - PhpPaul DixonView Answer on Stackoverflow
Solution 3 - PhpPatrick.SEView Answer on Stackoverflow