Development Tools Using PHP with MySQL Filtering Input for Queries Using a WHERE Clause

Storing results to a variable

At the end of the function, Randy stores the results to a variable called $product, and then returns that variable, like this:

$product = $results->fetch(PDO::FETCH_ASSOC);
return $product;

Wouldn't it be simpler to just return the results directly, without storing to a variable:

return $results->fetch(PDO::FETCH_ASSOC);

Is there any reason not to do this?

1 Answer

Erik McClintock
Erik McClintock
45,782 Points

Evan,

Though there may even be other reasons, one simple reason to store your results to a variable before returning them is that it allows for easier reuse and maintenance of your code. Consider that you might want to use what is returned by $results->fetch(PDO::FETCH_ASSOC); in more places than one: it would be much simpler to call $product over and over again rather than $results->fetch(PDO::FETCH_ASSOC); time and time again. Additionally, if you ever wanted to slightly tweak what you were accessing via $results->fetch(PDO::FETCH_ASSOC);, rather than having to go through and change every instance of $results->fetch(PDO::FETCH_ASSOC); that you have throughout your code, you would only need to edit it once: where you assigned it to your $product variable. It's the DRY principle: Don't Repeat Yourself. You also get a bonus from assigning it to a variable because you can name your variable something that makes sense for the data: reading $product makes a little more sense as to what you're getting somewhere over $results->fetch(PDO::FETCH_ASSOC);. That isn't very descriptive, but $product (or whatever else you choose to name your variable(s)) can be.

As I say, there may be other good reasons that are shared here, but even just at a basic level, to keep your code reusable and maintainable is one reason that you would store the results in a variable before returning them.

Erik