Is it bad practice to use temporary variables to avoid typing?

This example is perfectly fine, since you are using it in functions/methods.

The variable will be unset right after the method/function ends - so there's not much of a memory leak or what.

Also by doing this, you "sort of" implemented DRY - don't repeat yourself.

Why write so many $this->currentDatabase when you can write $db. And what if you have to change $this->currentDatabase to some other values?


Actually, you're not trying to avoid typing (otherwise, you'd use a completion mechanism in your editor), but you're just making your function more readable (by using "abbreviations") which is a good thing.

Drawbacks will show up when you start doing this to avoid typing (and sacrifice readability)


It depends what is the contract on $this->currentDatabase. Can it change at any time, after any method call? If it changes, are you supposed to keep on using the object you did when you made your first db call, or are you supposed to always us the current value? This dictates if you must always use $this->currentDatabase, or if you must always store it in a variable before using.

So, strictly speaking, this is not a style question at all.

But, assuming the member is never changed during function calls such as this, it makes no difference. I'd say storing it in a variable is slightly better, as it is easier to read and avoids a member access on an object at every operation. The compiler may optimize it away if it's good, but in many languages such optimizations are very difficult - and accessing a local variable is almost invariably faster than accessing a member of an object.