php - Dynamic MySQL table name within a class

321
class Patient {

   protected static $table_name = "siteA";
   public $id;
   public $first_dx;
   public $confidence;
   public $second_dx;
   public $path_dx;

}

I have simply shown the class attributes here. I have CRUD methods within the class but I haven't posted them simply to make this clear. The$table_name above in this case is siteA however I need to make this dynamic. When a user logins into my site their site is saved in the session (siteA, siteB, siteC etc) and I need the table name here to switch depending on the person logged in. The site is$_SESSION['user_site'], and I have tried to use this in curly braces, no quotes, quotes etc etc and no luck.

Clearly there is knowledge (skill) I am lacking. Can this be done? Any help is appreciated. Simon

268

Answer

Solution:

class Patient {

    protected static $table_name = "siteA";
    public $id;
    public $first_dx;
    public $confidence;
    public $second_dx;
    public $path_dx;

    public function __construct(){
        self::$table_name = $_SESSION['user_site'];
    }

}

Basically a constructor is a magic method that will be the first thing to execute when creating a new instance of your object, which is a perfect candidate for initializing values.

The reason you cannot use$_SESSION['user_site'] in the declaration of the properties is because they are being created at compile time where the session doesn't yet exist.

People are also looking for solutions to the problem: php - ZF2 ZendLog + Doctrine2

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.