Is there a valid technical use for returning by reference in PHP5

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?


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.

链接地址: http://www.djcxy.com/p/57258.html

上一篇: 在PHP中使用`&`关键字

下一篇: 在PHP5中是否有引用返回的有效技术用途?