The life of a minor minor prophet, not the rock


Tuesday, February 25, 2003
PHP scoping rules

We'll after 12 hours of banging my head against a wall I discover PHP doesn't follow C sytle scoping rules.  Here's how it works:

<?php
$a = 1; /* global scope */ 

function Test() { echo $a; /* reference to local scope variable */ }

Test(); ?>

This script will not produce any output because the echo statement refers to a local version of the $a variable, and it has not been assigned a value within this scope. You may notice that this is a little bit different from the C language in that global variables in C are automatically available to functions unless specifically overridden by a local definition. This can cause some problems in that people may inadvertently change a global variable. In PHP global variables must be declared global inside a function if they are going to be used in that function. An example:

<?php
$a = 1;
$b = 2;

function Sum() { global $a, $b;

$b = $a + $b; }

Sum(); echo $b; ?>

The above script will output "3". By declaring $a and $b global within the function, all references to either variable will refer to the global version. There is no limit to the number of global variables that can be manipulated by a function.


10:43:46 AM    

© Copyright 2003 Micah Alpern.

 

 


About me

Portfolio

Resume

 

 

enter your email for daily updates

powered by Bloglet

Subscribe to "Micah's Weblog" in Radio UserLand.

Send me email
Click here to send an email to the editor of this weblog.


Current Book
Social Network Analysis : Methods and Applications

 



February 2003
Sun Mon Tue Wed Thu Fri Sat
            1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28  
Jan   Mar