【问题标题】:Function will NOT execute the return statement in PHP函数不会在 PHP 中执行 return 语句
【发布时间】:2014-04-05 04:34:32
【问题描述】:

程序员朋友们好!由于某些奇怪的原因,该函数在执行第一个查询后不会返回任何内容。我注意到 $error 变量没有被返回,检查后我注意到在执行第一个查询后什么都不会返回。任何想法为什么会发生这种情况?

public function store_review(){
  $this->load->database();
  $error = NULL;

  $title = $this->input->post('title');   
  $raiting = $this->input->post('raiting');
  $description = $this->input->post('description');

  //Insert review
  $this->db->query("INSERT INTO reviews (title, raiting) VALUES (?, ?)", array($title, $raiting));    

  if ($this->db->affected_rows() == 1){
    $reviewID = $this->db->insert_id();

    //If review inserted insert description             
    $this->db->query("INSERT INTO reviews_descriptions (review_id, description) VALUES (?, ?)", array($reviewID, $description));

    if ($this->db->affected_rows() != 1){
      $error = 'Could not insert review description.';
    }           
  } 
  else {
    //If review could not be inserted duplicate exists
    $error = 'Review already exists.';
  }

  //THE FUNCTION WILL NOT EXECUTE ANY RETURNS AFTER THE FIRST QUERY
  return $error;
}

注意:我正在使用 CodeIgniter。

【问题讨论】:

  • 请说明您是如何运行store_review 并检查返回值
  • $error = $this->model->store_review(); if(isset($error)) echo '设置错误';

标签: php function codeigniter return


【解决方案1】:

这里是关键:

 $error = NULL;

当您将 NULL 分配给 $error 时,它会使 $error 成为一个集合变量,即使它为空。

因此,以下行会给您带来意想不到的结果:

$error = $this->model->store_review(); if(isset($error)) echo 'error is set';

检查的正确方法是使用is_null


这是测试我的答案的方法

<?php

$error = NULL;

if(is_null($error)){

echo "is_null | error not set \n";
}else{

echo "is_null |error set \n";
}


if(isset($error)){

echo "isset | error not set \n";
}else{

echo "isset |error set \n";
}

输出

is_null | error not set 
isset   | error set 

DEMO

【讨论】:

  • 谢谢你,但它仍然不起作用,再次,没有任何返回!如果不是 $error 我返回其他内容并尝试检查它是什么,那么什么都没有......就像我说的那样,在第一个查询返回语句之后似乎不适用于任何类型的数据。
  • @stacker 是你的插入查询成功
  • 是的,查询插入数据,但如果它不插入,它应该将错误存储在变量中并返回。问题是它永远不会返回任何东西,不是因为变量中的值,而是因为 return 语句不会执行。
猜你喜欢
  • 1970-01-01
  • 2019-08-12
  • 2014-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-07
  • 2019-03-09
  • 1970-01-01
相关资源
最近更新 更多