php - 奇偶数的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();
,然后在浏览器中得到一个白页,我的错误在哪里?
解决方案
您需要将该条件代码移动到构造函数中。
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';
}
}
// ...
}
推荐阅读
- node.js - 无法从“node_modules\@firebase\firestore\dist\rn\index.js”解析“./prebuilt.rn-f9cd27ba.js”
- typescript - 我无法通过 electron-main.dev.js/electron-main.js 的 tslint 问题构建类星体。项目设置后我从未编辑过这两个标准文件
- python - 使用 pickle 检索保存的对象时出错
- typescript - 为什么打字稿中的接口有时需要严格匹配属性,有时不需要
- pandas - 如何选择具有相同 id 并在另一列中具有所有缺失值的行
- python - cudatoolkit 和 cuda 的兼容性
- python-3.x - Tkinter 抛出异常,但代码仍然有效,为什么?
- android - 如何通过 Android Studio 从 Git 运行特定版本的应用程序?
- r - 使用正则表达式查找行
- .net - .NET:如何配置我自己的范围服务之一以进行静态访问?