I'm trying to pass a session variable that is already set, into a function for the purpose of using it's value to perform a calculation. $_SESSION['gv_1'] is set outside of the function and i want to pass it into the function to use it's value. I also want to set $gv_1 as a local variable inside the function so i do not have to keep writing $_SESSION['gv_1']. Then I want to return the new calculated value back to $_SESSION['gv_1'] for use outside of the function.
function sg_gc1($gv_1) {
$gv_1 = $_SESSION['gv_1'];
// more statements performing calculations using $gv_1
// Return new value to $_SESSION['gv_1'] for use outside of the function.
}
Just pass $_SESSION['gv_1']
as a parameter to sg_gc1()
. Then it will automatically be local in that function using the name of the parameter as you define it in sg_gc1()
. In this case it will be $gv_1
. Then just return that value.
function sg_gc1($gv_1) {
// do stuff to $gv_1
return $gv_1;
}
$variable = sg_gc1($_SESSION['gv_1']);
Doing this way doesn't hard code your session variable into your function so if in the future that value isn't in a session but another variable you do not need to refactor your code. It also makes your code easier to understand and maintain.
If you want to pass a variable into a function, you would pass it in when you call the function like so:
//define your function here
function sg_gc1($gv_1) {
//your code
}
$gv_1 = $_SESSION['gv_1'];<----get the session value and assign to local variable
sg_gc1($gv_1); <----call the function and pass in the value of the variable you created
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.