Page 1 of 1
Code defined outside function, solved
Posted: Thu Jan 21, 2010 3:33 pm
by scarface222
If you have code outside a function for example, on the same page, and that function is called, will $variable or and mysql queries be defined universally as a rule throughout multiple functions that use those variables on the same page?
Code: Select all
$variable=1;
function random($parameter1, $parameter2){
echo $variable=1;
}
function random2($parameter1, $parameter2){
echo $variable=1;
}
Re: Code defined outside function, quick question...
Posted: Thu Jan 21, 2010 4:57 pm
by AbraCadaver
I'm not sure I understand what you're asking, but do this and it should make it clear:
Code: Select all
$variable = 'start';
echo $variable;
random(null,null);
echo "after random() = " . $variable;
random2(null,null);
echo "after random2() = " . $variable;
function random($parameter1, $parameter2){
echo "inside random() = " . $variable;
$variable = 'random';
echo "inside random() = " . $variable;
}
function random2($parameter1, $parameter2){
echo "inside random2() = " . $variable;
$variable = 'random2';
echo "inside random2() = " . $variable;
}
Re: Code defined outside function, quick question...
Posted: Thu Jan 21, 2010 5:17 pm
by Eran
You need to consider how scope works in PHP - variables declared outside of functions and class methods are in a global scope, variables declared inside functions are in a local scope. The global and local scope are separate except for the use of the
global keyword, which allows variables from the global scope to be accessed inside a local scope. That is generally considered bad practice, since scoping is very important for the integrity of variable data and locality of changes - ie, changes you make in one place should not have unforeseen effects on another.
For more information, the manual is your best friend
http://php.net/manual/en/language.variables.scope.php
Re: Code defined outside function, quick question...
Posted: Thu Jan 21, 2010 6:42 pm
by scarface222
As usual, really appreciate the feedback, very well explained pytrin, and abra.