Home arrow PHP arrow Page 9 - The PHP Scripting Language

Static variables - PHP

This article describes the basics of the PHP scripting language, which is very easy to learn if you are familiar with any programming language. It is excerpted from chapter two of the book Web Database Applications with PHP and MySQL, written by Hugh E. Williams and David Lane (O'Reilly, 2004; ISBN: 0596005431).

  1. The PHP Scripting Language
  2. Creating PHP scripts
  3. Character encoding
  4. Expressions, Operators, and Variable Assignment
  5. switch Statement
  6. Changing Loop Behavior
  7. Automatic Type Conversion
  8. User-Defined Functions
  9. Static variables
  10. Managing include files
By: O'Reilly Media
Rating: starstarstarstarstar / 32
September 29, 2005

print this article



Variables can also be declared within a function as static. The static variable is available only in the scope of the function, but the value is not lost between function calls. Consider simple function count( ) that declares a static counter variable $count:

function count()
static $count = 0;
  return $count;
// prints 1
print count();
// prints 2
print count();

The first time the function count( ) is called, the static variable$countis set to zero, and incremented. The value of$countis maintained for subsequent calls.

Passing Variables to Functions

By default, variables are passed to functions by value, not by reference. Consider an example:

function doublevalue($var)
   $var = $var * 2;
$variable = 5;
print "\$variable is: $variable";

This produces the output:

$variable is: 5

The parameter$variable that is passed to the function doublevalue( ) isnít changed by the function. What actually happens is that the value 5 is passed to the function, doubled to be 10, and the result lost forever! The value is passed to the function, not the variable itself.

Passing parameters by reference

An alternative to returning a result or using a global variable is to pass a reference to a variable as a parameter to the function. This means that any changes to the variable within the function affect the original variable. Consider this example:

function doublevalue(&$var)
   $var = $var * 2;
$variable = 5;
print "\$variable is: $variable";

This prints:

$variable is: 10

The only difference between this example and the previous one is that the parameter$varto the function doublevalue( ) is prefixed with an ampersand character:&$var. The effect is a bit to hard to understand unless one learns low-level computer       languages, but it means that the parameter doesnít contain the value of the variableóinstead, it points to where the variable is stored in memory. The result is that changes to$varin the function affect the original variable$variableoutside the function.

If a parameter is defined as a reference, you canít pass the function a literal expression as that parameter because the function expects to modify a variable. PHP reports an error when the following is executed:

function doublevalue(&$var)
$var = $var * 2;
// The following line causes an error doublevalue(5);

Assigning by reference

Referencing with the ampersand can also be used when assigning variables, which allows the memory holding a value to be accessed from more than one variable. This example illustrates the idea:

$x = 10;
$y = &$x;
print $x;
print $y;

This fragment prints:


Because$yis a reference to$x, any change to$yaffects$x. In effect, they are the same variable. The reference$ycan be removed with:


This has no effect on$xor its value.

Assigning variables with a reference to another variable can also be done with the reference assignment operator=& with exactly the same outcome as shown in the previous example. The following fragment sets up three variablesó$x,$y, and $zóthat all point to the same value:

$x = 10;
// Use the reference assignment operator =& to assign a reference to $x
$y =& $x;
// Use the assignment operator = to copy a reference to $x
$z = &$x;
$x = 100;
// Prints "x = 100, y = 100, z = 100"
print "x = {$x}, y = {$y}, z = {$z}";

Default parameter values

PHP allows functions to be defined with default values for parameters. A default value is simply supplied in the parameter list using the = sign. Consider the heading( )function described earlier; here we modify the function definition to include a default value:

function heading($text, $headingLevel = 2)
   switch ($headingLevel)
case 1:
$result = "<h1>$text</h1>";
case 2:
$result = "<h2>$text</h2>";
case 3:
$result = "<h3>$text</h3>";
$result = "<p><b>$text</b></p>";
$test = "User-defined Functions";
print heading($test);

When calls are made to the heading( ) function, the second argument can be omitted, and the default value 2 is assigned to the$headingLevelvariable.

Reusing Functions with Include and Require Files

Itís valuable to be able to reuse functions in many scripts. PHP provides the include and require statements that allow you to reuse PHP scripts containing statements, function definitions, and even static HTML.

If you decide to reuse the bold( ) function from Example 2-3 in more than one script, you can store it in a separate include file. For example, you can create a file called functions.inc and put the bold( ) function in the file:

function bold($string)
print "<b>" . $string . "</b>";


Any PHP code in an include file must be surrounded by the PHP start and end script tags. The PHP script engine treats the contents of include files as HTML unless script tags are used.


You can then useincludeto provide access to the bold( ) function:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   http://www.w3.org/TR/html401/loose.dtd> <html>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  <title>Simple Function Call</title> </head>
<body bgcolor="#ffffff">
include "functions.inc";
// First example function call (with a string expression)
print "this is not bold ";
bold("this is bold ");
print "this is again not bold ";
// Second example function call (with a variable)
$myString = "this is bold";

Include files can also be used to incorporate resources such as static HTML or a set of variable initializations. The following example could be written to the file release.inc and included in all the scripts of an application:

<!-- Beta Release Only -->
    $showDebug = true;

Bothincludeandrequire read external include files, the only difference is in the behavior when a file canít be included:includeprovides a warning whereasrequireterminates the script with a fatal error.

When you are including a file that contains user-defined functions, or other mandatory content, you should use therequiredirective. We use therequiredirective in all of our code.

Theincludeandrequirestatements can be treated in the same way as other statements. For example, you can conditionally include different files using the following code fragment:

if ($netscape == true)
require "netscape.inc";
require "other.inc";

The file is included only if theincludestatement is executed in the script. The braces used in this example are necessary: if they are omitted, the example doesnít behave as expected.

Scripts can include more than one include file, and include files can themselves include other files. Writing scripts that useincludeorrequirecan lead to an include file being included and evaluated twice. To avoid problems with variable reassignments and function redefinitions, PHP provides theinclude_onceorrequire_onceconstructs statements that ensure that the contents of the file are included only once.

>>> More PHP Articles          >>> More By O'Reilly Media

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates


Dev Shed Tutorial Topics: