84

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

1

3 Answers 3

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

You can try it out by doing:

$x = foo();
var_dump($x);
Sign up to request clarification or add additional context in comments.

1 Comment

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: php.net/manual/en/migration71.new-features.php#122592
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!)

2 Comments

+1 but i wish i could +2, this is the more complete answer (includes question #4 regarding change in behavior between php versions)
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.
0

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.

3 Comments

You find it odd that you have to return anything when you explicitly said to PHP that you WILL return a string or null?
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.
This is actually confirmed behaviour. If there's no return on function, it will throw an error (PHP8.1) Return value must be of type ?string, none returned

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.