【发布时间】:2016-05-26 07:16:16
【问题描述】:
除非变量为空,否则我想让变量为 int。
这是我在 atm 上修复它的方式,但必须有更好的解决方案。
if ($answer == null) {
$all_questions[] = array (
'object_id' => (int) $stored_question->getObjectId(),
'question_code' => $stored_question->getQuestionCode(),
'answer' => $stored_question->getAnswer()
);
}
else{
$all_questions[] = array (
'object_id' => (int) $stored_question->getObjectId(),
'question_code' => $stored_question->getQuestionCode(),
'answer' => (int) $stored_question->getAnswer()
);
至少我希望有,因为这似乎是多余的。
【问题讨论】:
-
is_null($x)?$x:intval($x),但正如我在你的情况下看到的getAnswer返回一个整数作为字符串或 null 你应该在那里转换返回值 -
请注意,对于任何 @ PHP 认为是
false的 987654324@。因为在 PHP 中,null == false。在上面的代码之前,请执行以下任一操作:$answer = 0;或$answer="0";或$answer=0.0;或$answer=false;。这些都不是“null”,但它们都是== null。要测试 null,请使用=== null,而不是== null。