未定义变量CodeIgniter模型


Undefined variable CodeIgniter model

我需要理解为什么在

中没有定义country_id变量

模型
public function getCountry($country_id) {
    $this->db->select()->where('country_id', $country_id);
    $this->db->from('country');
    $query = $this->db->get();
    return $query->result(); 
}
控制器

public function country() {
     $json = array();
     $country_info = $this->country->getCountry($country_id);
     if ($country_info) {
         $json = array(
             'country_id'        => $country_info['country_id'],
             'name'              => $country_info['name'],
             'zone'              => $this->country->getZonesByCountryId($country_id),
             'status'            => $country_info['status']
         );
     }
     echo json_encode($json);
 }

结果:

消息:未定义变量:country_id

文件名:本地化/Countries.php

行号:12

消息:未定义变量:country_id

这里没有定义$country_id变量。它没有任何意义,因为它还没有被赋予任何东西。它就这么突然冒出来了。

public function country() {
     $json = array();
     $country_info = $this->country->getCountry($country_id);
     ....

你必须通过给它赋值来定义它....

public function country() 
{
     $json = array();
     $country_id = 3;  // <- define it here
     $country_info = $this->country->getCountry($country_id);
     ....

或者你可以把它作为函数的参数传入…

public function country($country_id) // <- pass it in
{
     $json = array();
     $country_info = $this->country->getCountry($country_id);
     ....