PHP变量有时不会传递给另一个函数

时间:2012-03-01 18:58:35

标签: php

编辑:更清晰

我遇到一个变量在函数调用之间消失的问题

首先我从这里开始,$ pid是一个取自JSON字符串的int

print "PID".$pid."\n";
$a['points'] = Algorithm::getpredictionForPlayer($pid);

我得到输出'PID12',它应该是

在Algorithm :: getpredictionForPlayer中接下来

static function getpredictionForPlayer($pid)
{

            print "PID2:  ".$pid."\n";
    $points =0;

    for ($i = 0; $i < 10; $i++)
    {
    print "algorithm: ".$pid."\n";
        $points += v4::predictPointsForPlayer($pid);
    }

    return intval($points/10);
}

偶尔我会得到'PID2:12',但更常见的是所有打印都是'PID2:' 在这段时间内,变量是否会消失?

2 个答案:

答案 0 :(得分:0)

您在全局范围内的变量是$ pid,但您将$ player_id传递给函数

print "PID".$pid."\n";
$a['points'] = Algorithm::getpredictionForPlayer($player_id);

然后,您的静态方法中有一个名为$ pid

的参数
static function getpredictionForPlayer($pid)

但这与全局范围中的变量不同。实际上,这将与您传入的$ player_id具有相同的值。如果您希望全局范围内的$ pid变量存在于静态方法中,则应将其传递给而不是$ player_id。

不过,你应该考虑一下你是否真的需要静态方法。通常它们会使测试变得困难,如果可能的话应该避免。你有玩家对象并在那上面调用方法getPrediction()吗?

答案 1 :(得分:0)

更改此行:

$a['points'] = Algorithm::getpredictionForPlayer($player_id);

对此:

$a['points'] = Algorithm::getpredictionForPlayer($pid);
相关问题