• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

PHP Variable Scoping

jgbishop

Senior member
Suppose I have the following code:

function one() {
var $a;
two();
}

function two() {
// I want to modify $a in this function
// Unfortunately, I cannot pass $a as a function parameter
}

I want to be able to modify variable $a in function two(). If I place the GLOBAL keyword in front of the $a in function two(), can I modify it appropriately? In that case, what happens when function one() returns? Does $a get destroyed, or is it still "global"?
 
a few ways to tacle this. You could use a static variable. That is a variable that is local to a function, but does not loose its value. or you could reference it as $GLOBALS['var'] or you could redefine the variable inside the function as global.

so we have

$a = 1;
$b = 1;
$c = 0;
function something() {
$GLOBALS['c'] = $GLOBALS['a'] + $GLOBALS['b'];
}

something();
echo $c;

That would print '2'

or we could do this

$a = 1;
$b = 1;
$c = 0;
function add() {
global $a, $b, $c;
$c = $a + $b;
}
add();
echo $c;

or finally we could do this.

or we coudl use a static.

function Test(){
static $a = 0;
echo $a;
$a++;
}

everytime you run that function a will increase by 1. So the first time a =0 then a=1 and so on.

personally, i perfer to use the $GLOBALS variable. But im curious. Why can't you pass the variable?

 
I cannot pass the variable as a parameter because function two() is a predefined callback. Unfortunately, there is no field that allows user data to be passed through (an unfortunate design). I need to manipulate a variable in function two(), and was wondering how best to do it. Thanks for the suggestions.
 
You can pass by ref in PHP.
Passing by Reference
You can pass variable to function by reference, so that function could modify its arguments. The syntax is as follows:


<?php
function foo (&$var)
{
$var++;
}

$a=5;
foo ($a);
// $a is 6 here
?>
 
Back
Top