【问题标题】:Can't access global variable in PHP codeigniter Model class.无法访问 PHP codeigniter Model 类中的全局变量。
【发布时间】:2014-04-03 13:12:39
【问题描述】:

我在 Codeigniter 中有一个扩展 CI_Model 的类。

我已经声明了一个全局数组 $data,但是我无法从我想要推送一些项目的函数中访问这个数组。 显示

遇到 PHP 错误消息:未定义变量:数据

致命错误:无法访问 /api/system/core/Model.php 第 51 行中的空属性

类代码:

class Subscription_collection_model extends CI_Model {
        public $data=array();
    /*
    |-----------------------------------------
    | Constructor
    |-----------------------------------------
    */

    function __construct() {
        parent::__construct();
            }

    function get() {

            $this->db->select('family.house_name,family.id,family_grade.amount');
            $this->db->from('family');
            $this->db->join('family_grade','family_grade.id = family.family_grade_id');
            $query = $this->db->get();
             if ($query->num_rows() > 0)
               {
                foreach ($query->result() as $row)
                    {
                        $this->findBalance($row->id);
                     }
                }    
         return $data;
        }


     function findBalance($id) {

        $this->db->where('family_id', $id);
        $this->db->select_sum('collecting_amount');
        $query = $this->db->get('subscription_collection');

           if ($query->num_rows() > 0)
               {
                foreach ($query->result() as $row)
                    {
                        array_push($this->$data,$row->collecting_amount);


                     }
                }
    }
}

【问题讨论】:

  • return $data; 应该是return $this->data 吧?也不是array_push($this->$data,而是array_push($this->data
  • k.thanks 但是当我将 $query 推送到 $data 时,它会显示错误。如何从 findBalance() 函数推送 $query 结果的每一行并在每一行中推送一个项目。

标签: php codeigniter scope public


【解决方案1】:

你有一个错字。你想打电话给$this->data 而不是$this->$data。 后者会假设,你想在实例上调用一个动态变量。

$prop = 'myProperty';
$this->$prop = 'test';

相同
$this->myProperty = 'test';

【讨论】:

    【解决方案2】:

    怎么样:

    return $this->data;
    

    【讨论】:

      猜你喜欢
      • 2016-11-12
      • 2012-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-17
      • 2014-04-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多