I've commented the code for easier readibility.
function logRequest($cached = false) {
// This function logs the number of two types of events: (1) cached and (2) uncached/upstream request
// References to frequently addressed array keys, for brevity
$lc = &$_SESSION['loads']['cache'];
$lu = &$_SESSION['loads']['upstream'];
// Add to one session variable or the other, depending on the type of event
$s = ($cached ? &$lc : &$lu);
$s = (isset($s) ? $s : 0) + 1;
// Begin dumping the counts to a file, but only every 25 calls for each client
if(($lc ?? 0) + ($lu ?? 0) < 25) return;
$logArray = (file_exists($logFile = '../runtime/requests.json') ? json_decode(file_get_contents($logFile),true) : []);
// Define array structure for dumping to a file
$today = (new DateTime())->format('Y-m-d');
$ac = &$logArray[$today]['cache access'];
$au = &$logArray[$today]['upstream request'];
// Do incrementing
$ac = (isset($ac) ? $ac : 0) + $lc;
$au = (isset($au) ? $au : 0) + $lu;
// Reset counters in the session
$lc = $lu = 0;
// Finally, save to file
file_put_contents($logFile, json_encode($logArray, JSON_PRETTY_PRINT));
}
The line I am talking about is this:
$s = ($cached ? &$lc : &$lu);
And the error is:
Parse error: syntax error, unexpected '&' in...
How do I go about assigning a reference in this case? Surely there must be a way to use the ternary operator, right?
P.S. I am a very casual programmer so I would be grateful if you could point out any other bad practices in my code.