0

I am wondering this question for a long time, how does PHP handle references are they a good idea to use and I can't explain better than using an example, lets look at the following class and then @ the comment of the setResult method.

Lets imagine we are using a model view controller framework and we are building a basic AjaxController, we only got 1 action method (getUsers) so far. Read the comments, and I hope my question is clear, how does PHP handle these kind of situations and is it true what I wrote about the x times in the memory @ the setResult docblock.

class AjaxController{
    private $json = array(
        'result' => array(),
        'errors' => array(),
        'debug' => array()
    );

    /**
     * Adds an error, always displayed to users if any errors.
     * 
     * @param type $description 
     */
    private function addError($description){
        $this->json['errors'][] = $description;
    }

    /**
     * Adds an debug message, these are displayed only with DEBUG_MODE.
     * 
     * @param type $description 
     */
    private function addDebug($description){
        $this->json['debug'][] = $description;
    }

    /**
     * QUESTION: How does this go in memory? Cause if I use no references,
     * the array would be 3 times in the memory, if the array is big (5000+)
     * its pretty much a waste of resources.
     * 
     * 1st time in memory @ model result.
     * 2th time in memory @ setResult ($resultSet variable)
     * 3th time in memory @ $this->json
     *
     * @param array $resultSet 
     */
    private function setResult($resultSet){
        $this->json['result'] = $resultSet;
    }

    /**
     * Gets all the users
     */
    public function _getUsers(){
        $users = new Users();
        $this->setResult($users->getUsers());
    }

    public function __construct(){
        if(!DEBUG_MODE && count($this->json['debug']) > 0){
            unset($this->json['debug']);
        }

        if(count($this->json['errors']) > 0){
            unset($this->json['errors']);
        }

        echo json_encode($this->json);
    }
}

Another simple example: What would be better to use technique A:

function example(){
    $latestRequest = $_SESSION['abc']['test']['abc'];

    if($latestRequest === null){
        $_SESSION['abc']['test']['abc'] = 'test';
    }
}

Or technique B:

function example(){
    $latestRequest =& $_SESSION['abc']['test']['abc'];

    if($latestRequest === null){
        $latestRequest = 'test';
    }
}

Thanks for reading and advise :)

1

1 Answer 1

2

In short: don't use references.

PHP copies on write. Consider:

$foo = "a large string";
$bar = $foo; // no copy
$zed = $foo; // no copy
$bar .= 'test'; // $foo is duplicated at this point.
                // $zed and $foo still point to the same string

You should only use references when you need the functionality that they provide. i.e., You need to modify the original array or scalar via a reference to it.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your answer, I now understand it. I just added another example, it would be awesome if you could take a look at that and advise me which technique is better to use. Once again, thanks :)
@MikeVercoelen, your second example where you set something that has been referenced is an appropriate usage of references, because you need that functionality to update the original data. It's not going to speed things up in any noticeable way, so don't use it because of that. Also, when you are done with a reference, you should unset() it to avoid accidentally reusing it later. And I realize the example was contrived, but generally a better solution is to avoid such complicated nested arrays altogether. Usually it means an object is more appropriate, which will lessen the need for refs.
If you find yourself in a situation where such a complex array is appropriate, then I would tend to use a reference as your example does just because it eliminates copy/paste errors. But this part of the answer is basically an opinion which people are free to disagree with.
thanks for the great description, and also about the unset, I really miss the lack of an article on how to write good PHP code, you know everyone has it's own coding techniques, and every tutorial tells you how to write a class, but no one explains how to think in code, how to write code in certain ways etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.