Click to See Complete Forum and Search --> : concatenation problem driving me nuts
strBean
10-27-2005, 02:17 PM
Hi
I have the following statement inside a function:
print '<div class="centeredform"><form method="post" action="'.$_SERVER['PHP_SELF'].'?trngSessID='.$session.'">';
The value of $session shows up if I put a print or echo statement on the page outside the function, but I get no value inside the function. I guess I need a lesson on variable scope in PHP. I assign a value to the variable at the top of the page, before any output...inside the functions, the var apparently doesn't exist.
What would you do?
bokeh
10-27-2005, 03:08 PM
Variables inside and outside functions are completely separate except for globals. In order to read from or write to an external variable from inside a function you must make it global to the function.
function your_function()
{
global $session;
print '<div class="centeredform"><form method="post" action="'.$_SERVER['PHP_SELF'].'?trngSessID='.$session.'">';
}
NogDog
10-27-2005, 03:18 PM
In the long run, it might be better to make it a parameter of your function. Global variables work fine, but have a habit of creating problems later as you modify your scripts and forget that some variable used in one place is used as a global somewhere else:
function your_function($session)
{
$url = urlencode("trngSessID=$session");
print "<div class='centeredform'><form method='post' action='{$_SERVER['PHP_SELF']}?$url'>";
}
# call the function as:
your_function($the_session_value);
strBean
10-27-2005, 03:18 PM
Hey, that worked, surprisingly. Funny, I just went to PHP.net to study up on variable scope, and I thought all it said about functions is that variables declared inside the function are local unless you use the global statement. I must have missed something.
Another thing that drove me nuts is that I knew one of you folks would have the answer in an instant, but my browser couldn't find webdeveloper.com for about a half hour!
But wait a minute! Other variables are available inside the function! Why not this one?
bokeh
10-27-2005, 04:10 PM
But wait a minute! Other variables are available inside the function! Why not this one?Only global ones like $_POST and $_ENV etc. Nogdog is right but there may be times when you write a function and you want the function to do more than one thing, for example to modify an external variable and return TRUE or FALSE. In these cases only global or access by reference will work.
strBean
10-27-2005, 04:18 PM
Okie doke. Thanks again.