Best practice accessing an array set within a class

Posted by user350599 on Stack Overflow See other posts from Stack Overflow or by user350599
Published on 2010-05-26T06:50:19Z Indexed on 2010/05/27 1:41 UTC
Read the original article Hit count: 241

Filed under:
|
|

I have created a basic class for a customer.

I haven't done this before and want to know the best way to access the data.

Should I have a get() method for every field in the customer array or should I simply pass the customer array back and access with the page.

i.e. Just return the array

class Customer {

  protected $id;
  protected $customer;

  public function __construct($customer_id) {
    $this->id = $customer_id;
    $this->set_customer();
  }

  protected function set_customer() {
    $query = mysql_query("SELECT * FROM customer WHERE id = '$this->id'");
    $this->customer = mysql_fetch_row($query);
  }

  public function get_customer() {
    return $this->customer;
  }
}

versus create a method for each item in the array

class Customer {

  protected $id;
  protected $customer;

  public function __construct($customer_id) {
    $this->id = $customer_id;
    $this->set_customer();
  }

  protected function set_customer() {
    $query = mysql_query("SELECT * FROM customer WHERE id = '$this->id'");
    $this->customer = mysql_fetch_row($query);
  }

  public function get_customer_name() {
    return $this->customer->customer_name;
  }

  ...

  ...
}

versus option 3 based on Tobias' feedback: (not sure if syntax is correct)

class Customer {

  protected $id;
  protected $customer;

  public function __construct($customer_id) {
    $this->id = $customer_id;
    return $this->set_customer();
  }

  protected function set_customer() {
    $query = mysql_query("SELECT * FROM customer WHERE id = '$this->id'");
    return mysql_fetch_row($query);
  }
}

© Stack Overflow or respective owner

Related posts about php

Related posts about class