Variable Scope

Any variable declared within a function will have a scope limited to the function. It's known as a local variable. It will not be available outside the function or within other functions.

Similarly, a variable delcared outside a function will not automatically be available within it.

In large projects, this can save you from accidentally overwriting the contents of a variable when you declare two variables with the same name in separate functions.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN">
<title>PHP</title>
<meta Name="Author" Content="Hann So">
</head>
<body>
<p>
<?php
$val = 5;

function Add($num1, $num2)
  {
  echo "val = ", $val, "<br />";
  $sum = $num1+$num2+$val;
  }
Add (3, 5);
echo "sum = ", $sum;
?>
</p>
</body>
</html>

View the effect


Functions | What is a Function? | Defining a Function | Calling a Function | Passing Data | Variable Scope | Global Access | Setting Default Values for Arguments | Passing Arguments by Reference | Returning Values from Functions | Returning References from Functions | Static Variables | Creating Variable Functions | Creating Conditional Functions | Creating Functions within Functions | Include Files | Require Statement | Testing a Function | Type-Testing Functions | Handling Errors Returned by Functions
© 2008: Hann So
email: hso@voyager.deanza.edu