#native_company# #native_desc#
#native_cta#

The ABC’s of PHP Part 4 – How Variable Am I? Page 3

By PHP Builder Staff
on April 1, 2009

Where does a variable belong?
One thing that very often confuses beginners to any language
is the subject of Scope.
“Scope” is how a variable is perceived by it’s surrounding code depending on it’s position in the source.
Put simply, it means that if your variable is boxed in (So
to speak), then code outside that box cannot see it’s
contents, unless you explicitly tell it that it can. This
method has the advantage of allowing you to use the same
variable name in several different places without an issue,
if your careful. In practice however, it’s normally not a
good idea.
So what is scope?
Consider the following PHP:

<?php

  $variable1 "one";

  
$variable2 "two";

  Function myfunction()

  {

    
$variable3 "three";

    Print 
"in my function V1 is : " $variable1 "n";

    Print 
"in my function V2 is : " $variable2 "n";

    Print 
"in my function V3 is : " $variable3 "n";

  }

  Print "Outside function : n";

  Print 
"in my function V1 is : " $variable1 "n";

  Print 
"in my function V2 is : " $variable2 "n";

  Print 
"in my function V3 is : " $variable3 "n";

  Myfunction();

  Print "Outside function : n";

  Print 
"in my function V1 is : " $variable1 "n";

  Print 
"in my function V2 is : " $variable2 "n";

  Print 
"in my function V3 is : " $variable3 "n";

?>



Don’t worry if you don’t understand it all just yet, all
that’s important is the positioning of the $variable =
?? lines
.
As you can see if you run it, in the first and last cases
$variable3 prints nothing, in-fact depending on how the
error reporting in your PHP is set up, you may even find
that an error is generated about missing variables.
What’s happening here, is that $variable3 can ONLY be
seen within it’s scope, which is the function. Outside of
that it cannot be seen, meanwhile $variable1 & 2 cannot be
seen inside the function as there scope only exists outside.
If we now add the following line just after the function
start, but before the $variable3 = ?? line :

Global $variable1,$variable2;

Now we re-run our script, you’ll see that V1 & V2 are now
available to the function. This means in theory you could
set that variable, then work with it inside the function. In
practice however, that’s not the best practice. The idea of
using functions is to pass in values, and return values
without using global variables, that however is a subject
for a different part of the series. For now, if your
variable doesn’t hold the value you expect, where you expect
always check it’s status, and see if it’s global or not.