Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does a php function return by default?

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

like image 645
user89021 Avatar asked Aug 02 '09 10:08

user89021


People also ask

What is default return type of function in PHP?

string when no string is returned.

What does a PHP function return?

PHP Functions returning value return stops the execution of the function and sends the value back to the calling code. You can return more than one value from a function using return array(1,2,3,4). Following example takes two integer parameters and add them together and then returns their sum to the calling program.

What is the default return of a function?

The default return value from a function is int. Unless explicitly specified the default return value by compiler would be integer value from function.

Does a PHP function have to return?

PHP functions do not need to return anything, and I doubt it would negatively affect the performance if you didn't return anything. If anything, it would positively affect the performance.


2 Answers

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

You can try it out by doing:

$x = foo();
var_dump($x);
like image 182
PatrikAkerstrand Avatar answered Oct 17 '22 09:10

PatrikAkerstrand


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

like image 39
Paul Dixon Avatar answered Oct 17 '22 07:10

Paul Dixon