Dan Blows
Dan Blows

Reputation: 21174

In PHP, is there an advantage to separating return from the calculation?

In PHP, I have a callback function using preg_match() (the exact contents are not relevant I think).

Is it better to calculate the result and assign to a variable, and then return that variable, or should I just return the result?

In other words, is it better to do this:

function a() {
   $result = preg_match();
   return $result;
}

or

function b() {
   return preg_match();
}

I'm thinking in terms of code style and performance. Is there a standard I should follow or is it really not important?

Upvotes: 2

Views: 118

Answers (3)

Marc B
Marc B

Reputation: 360572

There'd be a microscopic hit in performance to instantiate the $return variable, but that won't be noticeable in any practical situation. Generally I'd do the direct return, unless I needed to deal with that value further.

Upvotes: 2

mpdonadio
mpdonadio

Reputation: 2941

Personally, I try to return a variable, as I often want to log that variable somewhere during debug or at least have it available for a print_r or assert when something goes wonky. I also tend to do things like

$foo = step1($foo);
$foo = step2($foo);
$foo = step3($foo);
return $foo;

with string manipulation, and also when I think that requirements may change. This style makes it easy to comment/uncomment processing.

In general I code for clarity and self-documentation, but also try to anticipate how things may change, and therefore implement things so that impact is minimal.

Upvotes: 2

eykanal
eykanal

Reputation: 27017

From a performance standpoint there's no difference between the two cases.

Regarding coding style, it's a matter of personal preference. Personally, I would advocate the second, as it's cleaner and easier to read, but I don't think anyone would fault you either way.

Upvotes: 7

Related Questions