Watch out for reference vs value variables

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the dumb-mistakes-and-gotchas category.

Last Updated: 2024-11-21

I've once seen something like this fail (can't remember the language, but might have been some PHP version)

<?php

$originalToken = $user->apiToken;
$user->regenerateApiToken()

$this->assertNotEquals($originalToken, $user->apiToken); 
// Fails: i.e. the $originalToken is the same as the $user->apiToken,
// even though the `regenerateApiToken` method definitely changed the apiToken to
// something new.

What happened? The issue was that $originalToken was a reference to the token. When the token's value changed, it simply referred to this new value. This differs from the more common string behavior that assigning it to a variable assigns a cloned value.

Lesson

Automatic string cloning is not a given in all programming environments and you might sometimes have to explicitly clone your string to get a truly different object.