PHP
  Home arrow PHP arrow Page 9 - The PHP Scripting Language
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PHP

The PHP Scripting Language
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 31
    2005-09-29


    Table of Contents:
  • The PHP Scripting Language
  • Creating PHP scripts
  • Character encoding
  • Expressions, Operators, and Variable Assignment
  • switch Statement
  • Changing Loop Behavior
  • Automatic Type Conversion
  • User-Defined Functions
  • Static variables
  • Managing include files

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    The PHP Scripting Language - Static variables
    ( Page 9 of 10 )

    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;
      $count++;
      return $count;
    }
    // prints 1
    print count();
    // prints 2
    print count();

    The first time the function count( ) is called, the static variable $count is set to zero, and incremented. The value of $count is 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;
    doublevalue($variable);
    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;
    doublevalue($variable);
    print "\$variable is: $variable";

    This prints:

    $variable is: 10

    The only difference between this example and the previous one is that the parameter $var to 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       lan guages, 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 $var in the function affect the original variable $variable outside 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;
    $y++;
    print $x;
    print $y;

    This fragment prints:

    11
    11

    Because $y is a reference to $x , any change to $y affects $x . In effect, they are the same variable. The reference $y can be removed with:

    unset($y);

    This has no effect on $x or its value.

    Assigning variables with a reference to another variable can also be done with the ref erence 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>";
         
    break;
      
    case 2:
         
    $result = "<h2>$text</h2>";
         
    break;
      
    case 3:
         
    $result = "<h3>$text</h3>";
         
    break;
      
    default:
         
    $result = "<p><b>$text</b></p>";
       }
      
    return($result);
    }
    $test = "User-defined Functions";
    print heading($test);

    When calls are made to the heading( ) function, the second argument can be omit ted, and the default value 2 is assigned to the $headingLevel variable.

    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:

    <?ph p
    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 use include to 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>
    <head>
     
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
      <title>Simple Function Call</title> </head>
    <body bgcolor="#ffffff">
    <?php
    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";
    bold($myString);
    ?>
    </body></html>

    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 -->
    <?php
        $showDebug = true;
    ?>

    Both include and require read external include files, the only difference is in the behavior when a file can’t be included: include provides a warning whereas require terminates the script with a fatal error.

    When you are including a file that contains user-defined functions, or other manda tory content, you should use the require directive. We use the require directive in all of our code.

    The include and require statements 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";
    }
    else
    {
      
    require "other.inc";
    }

    The file is included only if the include statement 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 use include or require can lead to an include file being included and evaluated twice. To avoid problems with variable reassign ments and function redefinitions, PHP provides the include_once or require_once constructs statements that ensure that the contents of the file are included only once.



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

       

    PHP ARTICLES

    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...
    - Mastering WHILE Loops for PHP and MySQL
    - Method Chaining: Adding More Methods to the ...
    - Method Chaining in PHP 5
    - The Role of Interfaces in Applying the Depen...
    - Dependency Injection: Using a Setter Method ...
    - Using a Model Class with the Dependency Inje...
    - Injecting Objects Using Setter Methods with ...
    - Injecting Objects by Constructor with the De...
    - The Dependency Injection Design Pattern in P...
    - Performing Inferential Statistical Analysis ...
    - Performing Descriptive Statistical Analysis ...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 5 Hosted by Hostway
    Stay green...Green IT