Convenience variables: Do you or don't you

I was doing a code review the other day and I came across this piece of code:

$shopId = $this->session->shopId;if ($shopId !== null && is_numeric($shopId)) {    self::$SHOP['id'] = $shopId;}

I queried why the developer had done it. Why had he created this $shopId variable. Why hadn’t he just done this:

if ($this->session->shopId !== null && is_numeric($this->session->shopId)) {    self::$SHOP['id'] = $this->session->shopId;}

I call these convenience variables, that is, there is no point to them at all other than to make the rest of the code a little easier to type and to read (though it is no longer necessarily clear that this var relates to the one in the session object, nor will any changes to it be reflected in the original).So it got me thinking: How many people do this. Of the two, which would you do? Not for a right-vs-wrong debate, but more just out of curiosity.

And what is going on with this forum at the moment? I’m getting a lot of blank pages that are the result of a 500 internal server error, and it’s removing all of my line breaks

I often use convenience variables like this - for clarity, for less typing (and less chance of typos). I wonder if there’s a time saving to be had if the method used to retrieve the information from the class is not as straightforward as it looks, for example if it’s calling a query to get the shopid in the example it would call it only once rather than three times in your modified code.

I’m getting 500 errors as well, but I’m on a poor connection so get trouble a lot of the time.

No, it’s as simple as it looks :slight_smile: It’s just copying an object property into the current namespace and creating a new pointer for the garbage collector to clean up (if I understand the way that PHP’s internals works, at least).

I wonder if it’s taught that way somewhere, just in case of a more complex situation, which translates somewhere in the teaching or learning process into “you must always do this, it will always be better”. I know nothing of PHP’s internals (still learning how to use it, never mind what goes on behind the curtains) and have done nothing with classes at all, so may not be an issue.

I only use convenience variables if the value requires a function call, and that value is used multiple times - such as in the following:

$value = $obj->getValue();


if($value === $someVar) {}

In your scenario though, to just assign one variable to another seems pretty pointless.

I’m glad it’s not just me then. We’ve recently change our internet vendor and I thought this was a problem on my side (the blank pages, of course - not the internal server errors)!

I’ve been having it for days on my mobile and my PC. It’s really bugging the hell out of me now! I have to copy all posts in case the server errors when I submit and it gets lost