Lets say I’m storing an array or object called $_SESSION["logged_in_user"].
If I need to refer to it repeatedly throughout the script, which of the following is the “best practice”?
-
Use
$_SESSION["logged_in_user"]each time (i.e.$_SESSION["logged_in_user"]["first_name"])? -
Copy the object into a new variable like
$logged_in = $_SESSION["logged_in_user"]? -
Create a reference to the session variable like
$logged_in =& $_SESSION["logged_in_user"]
I’m probably overthinking this, but my main concerns are script overhead and readability. I’m not sure if referring to a session variable repeatedly is slower than referring to an inline-declared variable. I also don’t know if copying a session variable into a “regular” variable adds more overhead than is necessary. I do like the readability of $logged_in["first_name"] over $_SESSION["logged_in_user"]["first_name"].
So is there a best practice here, or does it really not matter?
You’re not overthinking it…. thinking is good!
I personally use symfony 1.4 to code in, which solves problems like these, but you may choose to stay lean 🙂
I’d think OO (object oriented). Create a user class. Then make calls like UserFactory::getCurrentUser() or User::getCurrentUser() which will return the currently logged in user object. Among the member variables of that class would be the user_id. However, you’ll be able to add addition functionality and data to that class.
Remember, thinking in OO means using abstract terms that are very close to the problem domain. User, Car, Order, etc. You don’t have to be specific and you don’t have to include all available information in that class for it to be “complete”, whatever that is. Only include the data that you need at the time (keep yagni in mind). The classes are illusions of the concrete, real-world things. Just as 3D modelling is an illusion of a real world thing.
Hope that helps…