views:

40

answers:

2

For instance:

// somefile.php
function doSomething() {
    // do lots of code, whatever...
    return $something;
}

// mainfile.php
include "somefile.php"
doSomething(); // ignored the return value, we don't need it here

What happens when a function in PHP returns a value but we don't care about it? Is something wrong with this behavior or should we always get the variable even if we'll never used it outside the function scope? How does PHP manage it's resources by returning a value that won't be used outside of the function scope?

+5  A: 

The return value is discarded. There is nothing wrong with doing that. Even functions without an explicit return do return null implicitly:

function foo() {}
var_dump(foo());  // NULL
Gumbo
just to add... think about `mysql_query()`. You can run `mysql_query()` by itself or you can assign its returned value to a variable. :) it doesn't matter if you just ignore it, all the code is still run.
Thomas Clayson
@Thomas Clayson: Sure, if you need the returned value for further processing, you need to handle it somehow. But if not, there is no need to store it.
Gumbo
+1 for "Even functions without an explicit return do return null implicitly:"
RobertPitt
A: 

There is nothing wrong with that, but

// do lots of code, whatever...

should make you somewhat suspicious. If you do not need the return value, chances are the function is doing too much. Check if the effect you actually want to achieve by calling the function can be extracted into a separate function. If so, do so and call this one instead.

Gordon
Seriously, why do you guys read so much into the comments? That was simply not to have the function body empty in the example with just a return call, now that would be suspicious...
Nazgulled
@Nazgulled mainly because you wrote *lots of code* in there. It's a common beginner's mistake to put too much into a function body, so I felt it worth mentioning (even without knowing your skill level).
Gordon
It was just an expression really, my actual function has only 18 lines of code if you count the comments :P Next time, I'll just type `// do some code` :)
Nazgulled