Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,783 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