函数不会在PHP中执行return语句

时间:2014-03-03 22:02:54

标签: php function codeigniter return

美好的一天同事们!出于某种奇怪的原因,在执行第一个查询后,函数不会返回任何内容。我注意到$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。

1 个答案:

答案 0 :(得分:0)

这是捕获:

 $error = NULL;

当您将NULL分配给$error时,它会将$ error设为变量,尽管它为null。

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

$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