tags:

views:

67

answers:

4

Hi, I am creating a php page with alot of functions which require to use the same variable (session id).

Am I able to write $ID = $_SESSION['ID']; and just use 'ID' in each function?

Rather than having to write $ID = $_SESSION['ID']; in each function?

Thanks

+1  A: 

Yes, you could do that but it would be better to create a SessionManager class that wraps session and exposes the values (like ID) via static getXX functions.

Try something like this:

class SessionManager {
    public static function getID() {
        return $_SESSION['ID'];
    }
}

then you can get the ID anywhere you want like this:

SessionManager::getID();
Andrew Hare
Thanks. Am I able to do something like this for using this code:$getid = "SELECT `username` FROM `users` WHERE `ID` = '$ID'"; $result=mysql_query($getid); $count=mysql_num_rows($result); $row = mysql_fetch_row($result);Rather than having to type that out everytime I need to access a row in the database? Thanks
Elliott
If you're regularly retrieving a username based on your stored session user id, then why not also store the username in a session variable at login?
da5id
That was just an example, I am retrieving alot more information using the user ID, jus wondering if I could "load" all the rows then call a row in a function.
Elliott
In that case I would probably write a function that retrieves all the information you want and returns it as an array.
da5id
+1  A: 

If you're looking to define a variable outside the function scope and be able to access it automatically from within functions, that's not possible.

You could define $ID = $_SESSION['ID']; outside of your function(s) scope, but then within each function you would have to add this:

global $ID;

This would make the $ID variable accessible to the function.

This is not suggested, for numerous reasons. If I were you, I would just call $_SESSION['ID'] directly from within the function(s).

Arms
A: 

if you declare $ID as a global variable you can use it in every function (after calling global $ID). but it will not update $_SESSION['ID'], if you want this too, you have to use references:

$ID = &$_SESSION['ID']
knittl
I don't think he's using classes
Peter Bailey
where was i talking about classes? ok, i see. public variable might be confusing. changed to global
knittl
A: 

(Just in case you haven't already thought of it) You could also convert all session variables 'en masse' at the start of each function thusly:

foreach ($_SESSION as $key => $value) { 
    $$key = $value; 
}
da5id