0

This is my USER class for getting user data.

require_once "classes/DB.php";

class USER {

    private $session_user_id = 1;
    //$session_user_id = $_SESSION["user_id"];

    private $user_data;
    public $username;
    public $first_name;
    public $last_name;
    public $profile_photo;

    private static $instance = null;

    //kthen objekt.
    private function __construct() {
        $db = DB::get_instance();
        $query = "SELECT * FROM `users` WHERE `user_id` = $this->session_user_id";
        $run_query = $db->mysqli->query($query);
        $this->user_data = $run_query->fetch_assoc();

        $this->username = $this->user_data["username"];
        $this->first_name = $this->user_data["first_name"];
        $this->last_name = $this->user_data["last_name"];
        $this->profile_photo = $this->user_data["profile"];
    }

    public static function get_instance() {
        if(!isset(self::$instance))
            self::$instance = new self;

        return self::$instance;
    }

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

}

$user = USER::get_instance();

Can anybody tell me which is the best method to make private properties and to get content using a public get_name(); method like echo $user->get_last_name()?

or to just echo property content? echo $user->last_name.

Extra question: how can I use $_SESSION variables inside a class? Should I pass it as a function parameter?

halfer
  • 19,824
  • 17
  • 99
  • 186
rexhin
  • 409
  • 1
  • 4
  • 11
  • 1
    In response to the "extra" question: `$_SESSION` is a superglobal, so you can access it from inside a class. Whether or not you should depends on what you plan to use it for, however. – ChicagoRedSox Jun 27 '14 at 21:08
  • 1
    I prefer getter functions, since public properties are open to external code setting them with invalid values. – halfer Jun 27 '14 at 21:17
  • I find "best method" pretty use-case-specific. But, creating getters and setters allows more flexibility (i.e. access modifiers), and also the ability to create *only* a getter. – ಠ_ಠ Jun 27 '14 at 21:21

1 Answers1

1

Firstly, you should view the popular framework designs for $_SESSION question.

In my opinion, it's better to use getter and setter methods for object-oriented approach. Because these variables cannot be modified from outside when compared with direct call of variables from class. Also, you can use protected variables are better than privates.

You can read these topics from Stack Overflow:

Why use getters and setters?

What is the point of getters and setters?

Community
  • 1
  • 1
user3566301
  • 182
  • 1
  • 13
  • Thank you very much for your answer. It would be great if you vote my post. Thanks again. @user3566301 – rexhin Jun 27 '14 at 21:37