0

My question is a follow up to the following question: What does it mean to start a php function with an ampersand?

The example code used in the question is this:

class FacebookRestClient {
...
    public function &users_hasAppPermission($ext_perm, $uid=null) {
        return $this->call_method('facebook.users.hasAppPermission', 
        array('ext_perm' => $ext_perm, 'uid' => $uid));
    }
...
}

Why would a reference be necessary when we already have a reference ($this)?

The chosen answer quotes the following from the PHP manual on Returning References

Returning by reference is useful when you want to use a function to find to which variable a reference should be bound. Do not use return-by-reference to increase performance. The engine will automatically optimize this on its own. Only return references when you have a valid technical reason to do so.

The second answer gives a reason why this technique was needed in PHP4. But I don't find the answer for why it is needed in PHP5 very convincing.

Does anybody know of any valid reason(s) for using this technique in PHP5?

Community
  • 1
  • 1
Jon Lyles
  • 325
  • 1
  • 3
  • 11

1 Answers1

2

Yeah, here's an example from my codebase.

I have a "factory" class for each model, such as UserFactory. When I call UserFactory::findOne() I return a reference to the model, which is stored in an array in UserFactory.

I do this so that if I get the user model and modify something in it, and then get it again later in my code, it is updated with the new information even though I never went back to the database.

For example:

<?php
$user = UserModel::findOne([ '_id' => 151 ]);
$user->status = 'disabled';

// Much later
$user = UserModel::findOne([ '_id' => 151 ]);
if ( $user->status != 'disabled' ) {
    // Do stuff
}

Returning by reference is a good way of accomplishing this without making two calls to my database.

Brandon Wamboldt
  • 15,241
  • 11
  • 49
  • 82