首页 > 解决方案 > 奇偶数的PHP数据选择

问题描述

我的数据库中有带有 ID 的表。我试图确保一个 API 用于偶数,以便另一个 API 用于奇数。

我需要用于不同数字的变量protected $apiKey = '5cef0578-acbc-4523-88c8-b47634ca3ba6';

我的代码:

class RandomOrgClient
{

    protected $url = 'https://api.random.org/json-rpc/2/invoke';
    protected $apiKey = 'MY KEY';
    protected $timeLimit = 300;


    function __construct()
    {
        $this->setTimelimit($this->timeLimit);
    }

我试图做类似的事情:

class RandomOrgClient
{

    protected $url = 'https://api.random.org/json-rpc/2/invoke';

    if ($games_count %2 == 0) {
        protected $apiKey = 'KEY FOR ODD NUMBER';
    } else { 
    protected $apiKey = 'KEY FOR EVEN NUMBER';
    }
    protected $timeLimit = 300;


    function __construct()
    {
        $this->setTimelimit($this->timeLimit);
        $games_count = DB::table('game_double')->count();

    }

但每次我收到错误Parse error: syntax error, unexpected 'if' (T_IF), expecting function (T_FUNCTION) or const (T_CONST)

我究竟做错了什么?我怎样才能纠正错误?

升级版:

我按照 2 人的建议进行了更改,但现在出现了另一个问题。1次生成的代码,第二次不要了,就是空白页。很可能是因为我在$games_count variable. 据我了解,偶数或奇数应该取自 ID 表。我将变量更改为$games_count = DB::table('game_double')->where('id')->get();,然后在浏览器中得到一个白页,我的错误在哪里?

标签: phplaravel

解决方案


您需要将该条件代码移动到构造函数中。

class RandomOrgClient
{
    protected $url = 'https://api.random.org/json-rpc/2/invoke';
    protected $apiKey;
    protected $timeLimit = 300;

    function __construct()
    {
        $this->setTimelimit($this->timeLimit);
        $games_count = DB::table('game_double')->count();
        if ($games_count %2 == 0) 
        {
            $this->apiKey = 'KEY FOR ODD NUMBER';
        }
        else 
        { 
            $this->apiKey = 'KEY FOR EVEN NUMBER';
        }
    }
    // ...
}

推荐阅读