【问题标题】:PHP typecasting null or intPHP 类型转换 null 或 int
【发布时间】: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

标签: php typecasting-operator


【解决方案1】:

首先声明共同认为你想要的两个代码

$all_questions[] = array (
        'object_id'     => (int) $stored_question->getObjectId(),
        'question_code' => $stored_question->getQuestionCode(),
      );

这取决于特定条件

$all_questions['answer'] = (is_null($answer)) ? 
  $stored_question->getAnswer() : (int) $stored_question->getAnswer() : 

【讨论】:

  • 赞成。完美匹配问题。 FWIW,对于大多数人这样编写代码,$answer 是要返回的值,不需要再次调用getAnswer()。在这种情况下,代码简化为... = is_null($answer) ? null : (int)$answer;。选项:没有必要分离出最终的属性分配;这可以作为数组初始化的一部分来完成。我通常会先“修复”:if (!is_null($answer)) $answer = (int)$answer; $all_questions[] = array ( 'object_id' => ..., 'answer' => $answer );
【解决方案2】:

试试这个:

$all_questions[] = [
    'object_id'     => (int) $stored_question->getObjectId(),
    'question_code' => $stored_question->getQuestionCode(),
    'answer'        => empty($answer)? $stored_question->getAnswer(): intval($stored_question->getAnswer())
];

【讨论】:

  • 不要使用empty。这对于可能让您感到惊讶的实体返回 true,例如字符串 "0.0"。所以这个答案不符合要求;它将返回整数或 null 以外的值。正如shivani's answer 所示,如果您想测试null,然后测试nullis_null=== null 是这样做的两种方式。
猜你喜欢
  • 2016-03-19
  • 1970-01-01
  • 2020-11-18
  • 2014-10-06
  • 2013-03-05
  • 1970-01-01
  • 2012-03-10
  • 2010-09-30
  • 1970-01-01
相关资源
最近更新 更多