Jump to content

[SOLVED] $_SESSION variable


Jonob

Recommended Posts

Just getting my head around using $_SESSION to store variables.

 

Lets assume that I am storing something like $_SESSION['company'] and I need to access this variable in all the functions in a file. Assume that my file looks as follows:

 

<?php
class test
{
  function foo()
  {
    //Do something here
  }
  function bar()
  {
    //Do something else here
  }
}
?>

 

Is there an easy way for me to do something like $company = $_SESSION['company'] at the top of the php file (or class), and then use $company_id in each function?

 

i.e. can I use $company_id as a variable in each function, without having to redeclare it inside each function??

 

Link to comment
https://forums.phpfreaks.com/topic/154865-solved-_session-variable/
Share on other sites

$_SESSION['company'] is a superglobal variable (available in all scopes.) Just use $_SESSION['company'] any place you need it.

 

$company = $_SESSION['company'] is just making a copy in a program variable that has the scope of wherever that statement is at and is just wasting memory and processing time.

$_SESSION['company'] is a superglobal variable (available in all scopes.) Just use $_SESSION['company'] any place you need it.

 

$company = $_SESSION['company'] is just making a copy in a program variable that has the scope of wherever that statement is at and is just wasting memory and processing time.

 

OK, makes sense. Thank you.

Not a session variable and using the global keyword inside of functions is another poor programming practice that php added to get around the fact that early versions of php did not support classes (which is what you use when you have closely related variables and functions that use those variables.)

No, I mean if he assigns a variable to the value of a session, he will need to make that variable global within the function.

 

And yeah, that's true, but he said he wanted to declare at the top of the script. If so, then it will have to be made global at some point.

$_SESSION variables are already global. Nothing more needs to be done to access them inside of functions and doing $company = $_SESSION['company'] is wasteful, unnecessary, and introduces a limit on the scope of the variable that would need to be worked around.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.