83

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) ...)

Kerem
  • 11,377
  • 5
  • 59
  • 58
user89021
  • 14,784
  • 16
  • 53
  • 65

3 Answers3

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

You can try it out by doing:

$x = foo();
var_dump($x);
Denilson Sá Maia
  • 47,466
  • 33
  • 109
  • 111
PatrikAkerstrand
  • 45,315
  • 11
  • 79
  • 94
  • Note that this is not true when you are using types in PHP >=7.1. You would expect this to work if return type is `?string` but it will give error like `TypeError: Return value must be of type ?string, none returned`. In such cases you need to explicitly return null. See: https://www.php.net/manual/en/migration71.new-features.php#122592 – user3563059 Nov 22 '22 at 05:01
40

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!)

Paul Dixon
  • 295,876
  • 54
  • 310
  • 348
  • +1 but i wish i could +2, this is the more complete answer (includes question #4 regarding change in behavior between php versions) – Jonathan Sep 17 '17 at 13:56
  • *But* using type hinting for return value, you have to omit a `return null;` on `: void` but have to `return null;` on (for example) `: ?string` when no string is returned. – rabudde Apr 11 '21 at 05:48
-1

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.

Patrick.SE
  • 4,444
  • 5
  • 34
  • 44
  • 1
    You find it odd that you have to return anything when you explicitly said to PHP that you WILL return a string or null? – Mike Doe May 08 '19 at 19:07
  • 1
    Well, if a function returns null by default, then I don't see why I should do it even if I'm declaring the return type. The compiler should deal with it. – Patrick.SE May 09 '19 at 14:45