具有三元运算符的参考分配

时间:2018-08-25 23:46:10

标签: php

为了方便阅读,我对代码进行了注释。

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));
}

我要说的是:

$s = ($cached ? &$lc : &$lu);

错误是:

  

解析错误:语法错误,...中出现意外的'&'

在这种情况下,我该如何分配参考?当然必须有一种使用三元运算符的方法,对吗?

P.S。我是一个非常随意的程序员,因此,如果您能指出我代码中的其他不良做法,我将不胜感激。

2 个答案:

答案 0 :(得分:2)

尝试

$cached ? $s = &$lc : $s = &$lu;

添加有关代码的一些说明。对不起,我的英语不好,我很抱歉用英语表达。

  

如果第一个子表达式的值为TRUE(非零),则对第二个子表达式求值,这是条件表达式的结果。否则,将评估第三个子表达式,即该值。

这来自php expressions manual

我们不能使用$s = $cached ? &$lc : &$lu;的原因是三元运算符需要一个表达式,但是&$lc&$lu不是表达式。

我们可以测试此代码

<?php
$a = 5;
$a;

没错。

但是这个

<?php
$a = 5;
&$a;

抛出错误。

  

解析错误:语法错误,意外的“&”,第3行的/usercode/file.php中的文件结尾应为

以上是我的看法,希望您能理解。

对我来说用英语太难了。(ㄒoㄒ)

答案 1 :(得分:0)

一种可行的选择是采用动态变量名称:

$s = &${$cached ? 'lc': 'lu'};

进一步阅读:https://stackoverflow.com/a/35772533/9986646