2017-12-10 4 views
0

Was ich habe, ist eine Produktklasse, können Sie ein Produkt über seine ID oder seine Produkt Nr. Erhalten. Also habe ich 2 Konstruktoren erstellt. Die Klasse ruft das Produkt über die Datenbank ab und ordnet das Ergebnis den Klassenvariablen zu.Zugang Attribute innerhalb Klasse

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); 
    } 
} 

Das Mapping funktioniert, (ich weiß, ich muss die Fehler zu fangen). Aber alle Werte sind null, wenn ich die toJson Methode aufruft.

Ich nenne es wie folgt aus:

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

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

    } 

} 

Und ja, ich weiß sicher, dass Daten zurückkommt, weil ich alle Elemente in der Mapping-Verfahren drucken. Aber warum sind die Daten verschwunden, wenn ich sie über toSon erreiche?

Antwort

1

Ihre Methode withId ruft loadByID auf, wodurch eine neue Instanz Ihres Modells erstellt wird. Es lädt die Daten nicht in das Modell, das in withId erstellt wurde, das zurückgegeben wird

+1

Ugh, ich sehe es. Vielen Dank! – da1lbi3

Verwandte Themen