views:

46

answers:

1

This may be a silly question to some, but I was curious how would PHP react to something such as:

$blog_title = &$author->get_blog()->get_title();

I'm assisting someone with some upgrades to an in house php framework. There is some serious method chaining going on, repeatedly in some places. I'd like to make the code more readable without unnecessary copies of variables. I'm unable to overhaul the code, so I have to work with what I've got.

I know it's probably not a great practice, but what are the potential downsides?

+3  A: 

It would only make sense when the function actually returns a reference (my educated guess is it probably doesn't), which would mean you either hope the return stays static for the complete script, or you're breaking things. You could define your own short function or callback which will do the chaining for you as the next best thing.

By all means, keep a return of a function in a variable if it only needs to be evaluated once, but don't expect some magic from a reference when the return of a function is not one.

If the function does return a reference, the code is probably using references where they don't make sense, and you should fix that asap :P.

Wrikken
It's honestly been some time since I dabbled with PHP. Is it not bad practice to create variables for things like this? What about a scenario where you don't want to have to type `$this->name`?
Doomspork
"don't want to have to type" is always a bad reason to alter code, and the main reason why there's code-completion in editors. By all means, cache function outcomes and variables if you're sure they won't change, but don't use references to avoid typing, references can easily foul up code in hard to detect ways.
Wrikken