dr637349 2017-12-10 11:38
浏览 42
已采纳

访问类中的属性

What I have is a product class, you can get a product via its id or its product nr. So I have created 2 constructors. The class is retrieving the product via the database and mapping the result to the class variables.

class Partnumber extends CI_Model
{
    private $partNr;
    private $description;
    private $type;

    public function __construct() {
    }

    public static function withId( $id ) {
        $instance = new self();
        $instance->loadByID( $id );
        return $instance;
    }

    public static function withNr($partnumber) {
        $instance = new self();
        $instance->getIdFromPartnumber($partnumber);
        return $instance;
    }

    protected function loadByID( $id ) {
        $instance = new self();
        $instance->getPartnumberFromId($id);
        return $instance;
    }

    private function getIdFromPartnumber($partnumber){
        $this->db->select("*");
        $this->db->from('part_list');
        $this->db->where('part_number', $partnumber);
        $query = $this->db->get();

        return $query->result_object();
    }

    //get the partnumber from an part id
    private function getPartnumberFromId($partId){
        $this->db->select("*");
        $this->db->from('part_list');
        $this->db->where('id', $partId);
        $query = $this->db->get();

        $this->mapToObject($query->result());
    }

    private function mapToObject($result){
        $this->partNr = $result[0]->Part_number;
        $this->description = $result[0]->Description;
        $this->type = $result[0]->Type;
    }

    public function toJson(){
        return json_encode($this->partNr);
    }
}

The mapping works, (I know, I have to catch the errors). But all the values are null when I calling the toJson method.

I call it like this:

class TestController extends MX_Controller{
    public function __construct(){
        parent::__construct();
        $this->load->model('Partnumber');
    }

    public function loadPage() {
           $p = Partnumber::withId(1);
           echo $p->toJson();

    }

}

And yes, I know for sure that data is coming back, because I can print all the items in the mapping method. But why is the data gone when I acces it via toJson?

  • 写回答

1条回答 默认 最新

  • dqsp60748 2017-12-10 11:44
    关注

    Your method withId calls loadByID which creates a new instance of your model. It does not load the data into the model that was created in withId which is returned

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?