php book,learn php online,complete php book

Document Sample
php book,learn php online,complete php book Powered By Docstoc
					                                                                                                        4
                                                                             1
              Variables, Constants , and Data
                                       Types

 In the previous chapter, we met PHP variables and saw briefly how to use them. We stated that PHP
 variables must begin with the dollar character ($) and that PHP is a weakly-typed language – that is,
 variables can contain any type of data and do not have to be predefined as strings, integers, etc. We also
 saw how we can use PHP variables to extract data from an HTML form.

 In this chapter, we will look in more detail at variables and their data types. We will consider the issue of
 data type juggling in more detail, and we will look at some of the functions we can use to manipulate
 variables. We will also see how to assign a name to a constant value, which remains the same throughout
 the program.


Data Types
 PHP has three basic data types: integer, double and string. There are also some not-so-basic types, namely
 arrays and objects, which are discussed in later chapters. Every variable has a specific type, though, as
 we’ve already mentioned, a variable’s type may change on the fly as the variable’s value changes, or as the
 code otherwise dictates.

 Integers use four bytes of memory and are used to represent ordinary, non-decimal numbers in the range of
 approximately –2 billion to +2 billion. Doubles, also known as float (floating-point) or real numbers, are
 used to represent numbers that contain a decimal value or an exponent. Strings are used to represent non-
 numeric values, like letters, punctuation marks, and even numerals.

     2             // This is an integer

 1
  [JHS] I've added a bit of an introduction to avoid the abrupt start to the chapter. The chapter
 seems technically accurate, but I think we could do with a bit more explantion in places. The
 major topic which is omitted from this chapter is HTTP environment variables. We need a large
 section on these. While a complete listing should form an appendix, we need to show in this
 chapter how to access HTTP variables from PHP and to give a couple of practical examples: it
 would be good if these could be incorporated into the Job Application Form.




                                     TEAM FLY PRESENTS
      2.0           // This is a double
      "2"           // This is a string
      "2 hours"     // This is another string

  Many languages contain a Boolean data type to represent the logical values TRUE and FALSE. PHP does
  not. It instead uses expressions of the other three basic types that evaluate to either true or false values.
  Among integers, 0 (zero) evaluates as a false value, and any non-zero integer evaluates as a true value.
  Similarly, the double value 0.0 (or equivalents, such as 0.000) evaluates to FALSE, and any non-zero
  value evaluates to TRUE. Among strings, the empty string evaluates to FALSE. It is represented as a pair of
  quotation marks containing nothing: "". Any non-empty string evaluates to TRUE.


Literals and Identifiers
  Variables, constants, functions and classes must have distinct labels in order to be useful. Within these
  labels there is a distinction between literals and names.

  Literals are raw data, what you see is what you get. You can have number literals (e.g. 786) or string
  literals (e.g. "a quoted string"). Basically, you cannot make a literal mean something other than what it
  literally means. Names, on the other hand, acquire their meaning by convention or by decree. The
  connection between a name and its meaning is arbitrary, a rose, as you know, "by any other name would
  smell as sweet". Names used in programming are called identifiers.

  Identifiers in PHP are case-sensitive, so $price and $Price are different variables. Built-in functions
  and structures are not case-sensitive, however; so echo and ECHO do the same thing. Identifiers may
  consist of any number of letters, digits, underscores, or dollar signs but cannot begin with a digit.


Data Values
  In addition to its meaning in the program, an identifier also has a value, which is a data item of a specific
  data type. If the identifier is able to change its value through the course of the program it is called a
  variable, whereas if the identifier has a fixed value, it is known as a constant.


Constants
  Constants are values that never change. Common real-life constants include the value of pi (approx. 3.14),
  the freezing point of water under normal atmospheric pressure (0° C), and the value of "noon" (12:00). In
  terms of programming, there are two types of constants: literal and symbolic constants. Literal constants are
  simply unchanging values that are referred to directly, without using an identifier.

  When we use the term “constants”, we normally are referring to symbolic constants. Symbolic constants are
  a convenient way to assign a value once to an identifier and then refer to it by that identifier throughout
  your program.

  For example, the name of your company is a rather constant value. Rather than include the literal string
  "Phop's Bicycles" all throughout your application, you can define a constant called COMPANY with
  the value "Phop's Bicycles" and use this to refer to the company name throughout your code. Then, if
  the name ever does change as a result of a merger or a marketing ploy, there is only one place where you
  need to update your code: the point at which you defined the constant. Notice that constant names, unlike
  variable names, do not begin with a dollar sign.

Defining Constants
  The define() function is used to create constants:




                                            TEAM FLY PRESENTS
      define("COMPANY", "Phop's Bicycles");
      define("YELLOW", "#FFFF00");
      define("VERSION", 3);
      define("NL", "<BR>\n");

  In the last example, we define a constant called NL that represents an HTML break tag followed by a
  newline character. Essentially, we have created a coding shortcut, since “<BR>\n ” is a commonly used
  combination. By convention, programmers define constants using all capital letters. A constant may contain
  any number or string value. Once constants are defined, they can be used in lieu of their values:

      echo("Employment at " . COMPANY . NL);

  This is equivalent to:

      echo("Employment at Phop's Bicycles<BR>\n");

  Notice that the constant appears outside of the quotation marks. The line:

      echo("Employment at COMPANY NL");

  Would literally print "Employment at COMPANY NL" to the browser.

defined()
  The defined() function allows you to determine whether or not a constant exists. It returns 1 if the
  constant exists and 0 if it does not:

      if (defined("YELLOW")) {
         echo ("<BODY BGCOLOR=" . YELLOW . ">\n");
      }


Built-in Constants
  PHP includes several built-in constants. TRUE and FALSE are pre-defined with respective true (1) and false
  (0 or empty string) values. The constant PHP_VERSION indicates the version of the PHP parser that is
  currently running, such as 3.0.11. The constant PHP_OS indicates the server-side operating system on
  which the parser is running.

      echo(PHP_OS);        // Prints "Linux" (for example)

  __FILE__ and __LINE__ hold the name of the script that is being parsed and the current line number
  within the script. (There are two underscore characters before and after the names of these constants.)

  PHP also includes a number of constants for error reporting: E_ERROR, E_WARNING, E_PARSE, and
  E_NOTICE.

  Furthermore, PHP utilizes a number of predefined variables that provide information about the environment
  on which PHP is running. A full list is included in Appendix ?. In order to view what these variables are set
  to on your computer, you can use the function phpinfo() as shown in the following code:

      <HTML>
      <!-- phpinfo.php -->




                                     TEAM FLY PRESENTS
       <BODY>

           <?php
              phpinfo()
           ?>

       </BODY>
    </HTML>

This should produce the page shown in the screenshot below:




                                       TEAM FLY PRESENTS
Variable Declaration and Initialization
  Different to constants, a variable is automatically declared in PHP when you assign a value to it.
  Assignment is accomplished with the assignment operator (=). Note that the assignment operator (=) and
  the equality operator (==) are different in PHP, as we shall see in the next chapter.

      $num_rows = 10;

      $product = "Tire Pump";

      $price = 22.00;
      $shipping = 5.00;
      $total = $price + $shipping;



Type Juggling and Type Casting
  As mentioned previously, every PHP variable has a data type. That type is determined automatically by the
  value that is assigned to the variable.

      $a = 1;         // $a is an integer
      $a = 1.2;       // Now it's a double
      $a = "A";       // Now it's a string

  As we’ll learn in the next few sections, there are also ways to explicitly specify the type of a variable.

String Conversion and Type Juggling
  If you perform a numerical operation on a string, PHP will evaluate the string as a number. This is known
  as string conversion, although the variable containing the string itself may not necessarily change. In the
  following example, $str is assigned a string value:

      $str = "222B Baker Street";

  If we attempt to add the integer value 3 to $str, $str will be evaluated as the integer 222 for purposes of
  the calculation:

      $x = 3 + $str;        // $x = 225;

  But the $str variable itself has not changed:

      echo ($str);        // Prints: "222B Baker Street"

  String conversion follows a couple of rules:

     ❑    Only the beginning of the string is evaluated as a number. If the string begins with a valid numerical
          value, the string will evaluate as that value; otherwise it will evaluate as zero. The string "3rd
          degree" would evaluate as 3 if used in a numerical operation, but the string "Catch 22" would
          evaluate as 0 (zero).




                                       TEAM FLY PRESENTS
     ❑     A string will be evaluated as a double only if the double value being represented comprises the entire
           string. The strings "3.4", "-4.01", and "4.2e6" would evaluate as the doubles 3.4, -4.01, and
           4.2000000. However if other non-double characters are included in the string, the string will evaluate
           as an integer: "3.4 children" would evaluate as the integer 3. The string "-4.01 degrees"
           would evaluate as the integer -4.

  In addition to string conversion, PHP performs type juggling between the two numeric types. If you
  perform a numerical operation between a double and an integer, the result will be a double:

      $a   =   1;             //   $a   is   an integer
      $b   =   1.0;           //   $b   is   a double
      $c   =   $a + $b;       //   $c   is   a double (value 2.0)
      $d   =   $c + "6th";    //   $d   is   a doube (value 8.0)


Type Casting
  Type casting allows you to explicitly change the data type of a variable:

      $a   =   11.2;          //   $a is a double
      $a   =   (int) $a       //   Now it's an integer (value 11)
      $a   =   (double) $a    //   Now it's a double again (value 11.0)
      $b   =   (string) $a    //   $b is a string (value "11")

  (array) and (object) casts are also allowed. (integer) is a synonym for (int). (float) and
  (real) are synonyms for (double).


Variable Variables
  PHP supports variable variables. Ordinary variables have dynamic values: you can set and change the
  variable's value. With variable variables, the name of the variable is dynamic. Variable variables generally
  create more confusion than convenience (especially when used with arrays). They are included here for the
  sake of completeness; but in practice, they are of little real benefit. Here is an example of a variable
  variable:

      $field = "ProductID";
      $$field = "432BB";

  The first line of the code above creates a string variable called $field and assigns it the value
  "ProductID". The second line then uses the value of the first variable to create the name of the second
  variable. The second variable is named $ProductID and has the value "432BB". The following two lines
  of code produce the same output:

      echo ($ProductID); // Prints: 432BB
      echo ($$field);    // Prints: 432BB



Useful Functions for Variables
  PHP has a number of built-in functions for working with variables.

gettype()
  gettype() determines the data type of a variable. It returns one of the following values:




                                               TEAM FLY PRESENTS
    ❑    "integer"
    ❑    "double"
    ❑    "string"
    ❑    "array"
    ❑    "object"
    ❑    "class"
    ❑    "unknown type"

 We shall see more on arrays, objects and classes in later chapters. An example using gettype() may be:

     if (gettype ($user_input) == "integer") {
        $age = $user_input;
     }

 Related functions: isset(), settype()

settype()
 The settype() function explicitly sets the type of a variable. The type is written as a string and may be
 one of the following: array, double, integer, object or string. If the type could not be set then a
 false value is returned.

     $a = 7.5;                       // $a is a double

     settype($a, "integer");         // Now it's an integer (value 7)

 settype() returns a true value if the conversion is successful. Otherwise it returns false.

     if (settype($a, "array")) {
        echo("Conversion succeeded.");
     } else {
        echo ("Conversion error.");
     }


isset() and unset()
 unset() is used to destroy a variable, freeing all the memory that is associated with the variable so it is
 then available again. The isset() function is used to determine whether a variable has been given a
 value. If a value has been set then it returns true.

     $ProductID = "432BB";
     if (isset($ProductID)) {
       echo("This will print");
     }

     unset($ProductID);
     if (isset ($ProductID)) {
       echo("This will NOT print");
     }




                                    TEAM FLY PRESENTS
  Related functions: empty()

empty()
  empty() is nearly the opposite 2of isset(). It returns true if the variable is not set, or has a value of
  zero or an empty string. Otherwise it returns false.

      echo empty($new);            // true

      $new = 1;
      echo empty($new);            // false

      $new = "";
      echo empty($new);            // true

      $new = 0;
      echo empty($new);            // true

      $new = "Buon giorno";
      echo empty($new);            // false

      unset ($new);
      echo empty($new);            // true


The is...() functions
  The functions is_int(), is_integer(), and is_long() are all synonymous functions that
  determine whether a variable is an integer.

  is_double(), is_float(), and is_real() determine whether a variable is a double.

  is_string(), is_array(), and is_object() work similarly for their respective data types.

      $ProductID = "432BB";
      if (is_string ($ProductID)) {
        echo ("String");
      }


The ...val() functions
  PHP provides yet another way to explicitly set the data type of a variable: the intval(), doubleval(),
  and strval() functions. These functions cannot be used to convert arrays or objects.

      $ProductID = "432BB";
      $i = intval($ProductID);               // $i = 432;

  The intval() function can take an optional second argument representing the base to use for the
  conversion. By default, the function uses base 10 (decimal numbers). In the example below, we specify
  base 16 (hexadecimal numbers):

  2
    [kk] Empty() is NOT the opposite of isset() and this is important do know. Unlike Perl, PHP3
  internally does not signal “undef” (undefined value) and “”/0 (zero value) in a different way and
  isset() is really the only way to determine this difference. That is why next(), prev() and the like
  are broken.




                                          TEAM FLY PRESENTS
     $ProductID = "432BB";
     $i = intval ($ProductID, 16);        // $i = (decimal)275131 ;

 "432BB" was interpreted as a five-digit hexadecimal number.


Building an Online Job Application Form
 The sample application begun in the previous chapter illustrates how PHP variables are automatically
 created when HTML form data are submitted to a PHP script. Let's introduce a few more variables by
 adding more elements to the HTML form.

     <HTML>
     <!-- jobapp.html -->
        <BODY>
            <H1>Phop's Bicycles Job Application</H1>
            <P>Are you looking for an exciting career in the world of cycling?
               Look no further!
            </P>
            <FORM NAME='frmJobApp' METHOD=post ACTION="jobapp_action.php">
               Please enter your name:
               <INPUT NAME="applicant" TYPE="text"><BR>
               Please enter your telephone number:
               <INPUT NAME="phone" TYPE="text"><BR>
               Please enter your E-mail address:
               <INPUT NAME="email" TYPE="text"><BR>

                Please select the type of position in which you are interested:
                <SELECT NAME="position">
                   <OPTION VALUE="a">Accounting</OPTION>
                   <OPTION VALUE="b">Bicycle repair</OPTION>
                   <OPTION VALUE="h">Human resources</OPTION>
                   <OPTION VALUE="m">Management</OPTION>
                   <OPTION VALUE="s">Sales</OPTION>
                </SELECT><BR>

                Please select the country in which you would like to work:
                <SELECT NAME="country">
                   <OPTION VALUE="cn">Canada</OPTION>
                   <OPTION VALUE="cr">Costa Rica</OPTION>
                   <OPTION VALUE="de">Germany</OPTION>
                   <OPTION VALUE="uk">United Kingdom</OPTION>
                   <OPTION VALUE="us">United States</OPTION>
                </SELECT><BR>

              <INPUT NAME="avail" TYPE="checkbox"> Available immediately<BR><BR>
              <INPUT NAME="enter" TYPE="submit" VALUE="Enter">
           </FORM>
        </BODY>
     </HTML>




                                   TEAM FLY PRESENTS
In Chapter 3 it was demonstrated that for every element in a submitted HTML form, a PHP variable is
created in the receiving script. Therefore, our script, "jobapp_action.php", will have the following
global variables available to it automatically: $applicant, $phone, $email, $position,
$country, $avail, and $enter. The value of these variables (except for $enter) will be determined
by the user's input.

What is the data type of these variables? To find out, we can use the gettype() function in
jobapp_action.php:

    <HTML>
    <!-- jobapp_action.php -->
       <BODY>

           <?php
              echo(gettype($applicant));
           ?>

       </BODY>
    </HTML>

In so doing, we would discover that our script prints the word "string" every time, regardless of the
value entered in the "applicant" text element. It even prints "string" if the form is submitted with no
value entered. PHP automatically treats all submitted form data as strings. In most cases, this does not
become an issue, even if your form data represent numeric values. PHP will perform string conversion and




                                       TEAM FLY PRESENTS
type juggling as needed for calculations. In the event that you find it necessary to explicitly set the type of
data, however, you have the three 3different previously described techniques at your disposal: type casting,
the settype() function, and the ...val() functions.

For a text element, a PHP variable will always be created when the form is submitted. If we leave the
applicant text element blank and submit the form, a PHP variable called $applicant will be created
in jobapp_action.php with the value "" (empty string). Checkbox elements, such as avail in our
example, do not behave like text elements. An $avail variable will only be created if the checkbox was
checked "on" when the form was submitted. If the checkbox is left unchecked, no variable will be created.
We can use isset() in our jobapp_action.php script to determine whether or not the $avail
variable exists, and therefore whether the avail checkbox element was checked:

    <HTML>
    <!-- jobapp_action.php -->
       <BODY>

            <?php
               echo (isset($avail) . "<BR>\n");                 // Prints 1 if exists
                                                                // Prints 0 if not

                 echo ($avail);                                 // Prints "on" if exists
                                                                // Prints nothing if not
            ?>

       </BODY>
    </HTML>

The isset() function will return either 1 or 0, and $avail's value will either be "on" or non-existent. It
would be more convenient if $avail behaved like a Boolean variable and contained a value of 1 if the
checkbox was checked and 0 if it was unchecked. This can be achieved easily enough by reassigning
$avail to equal the output of the isset() function:

    <HTML>
    <!-- jobapp_action.php -->
       <BODY>

            <?php
               $avail = isset($avail); // Convert to boolean
               echo ($avail);          // Prints 1 if checked
                                       // Prints 0 if unchecked
            ?>

       </BODY>
    </HTML>

This is a quick and easy way to convert "checkbox" variables into "boolean" variables. PHP does not
actually contain a boolean data type. Instead it uses an integer with either a 0 (false) or non-zero (true)
value. After the code above has executed, the line echo (gettype($avail)); would reveal that it is
now of type "integer".




3
 [kk] four, neutral additions (+0, +0.0 or .””) are not in the online PHP3 manual, but they do
work and they are a classic for this operation




                                    TEAM FLY PRESENTS
Adding a Constant
  Earlier in this chapter, I demonstrated how to use a constant to store the name of the company. By storing
  this information in only one place, it is much easier to update the application if the name of the company
  changes, or if you want to use the same code for more than one company. In order to achieve this flexibility
  in our job application program, we need to make our HTML form dynamic by including PHP scripts in it.
  This means that we have to rename the file from "jobapp.html" to "jobapp.php". Otherwise, PHP
  scripts will not be parsed by the web server.

  Once we have renamed the file, we can add our PHP tags that define and use the needed constant:

      <HTML>
      <!-- jobapp.php -->
         <BODY>

             <?php
                define ("COMPANY", "Phop's Bicycles");
             ?>

             <H1><?php echo (COMPANY); ?> Job Application</H1>
             <P>Are you looking for an exciting career in the world of cyclery?
                Look no further!
             </P>

             <FORM NAME='frmJobApp' METHOD=post ACTION="jobapp_action.php">
                Please enter your name:
                <INPUT NAME="applicant" TYPE="text"><BR>
                Please enter your telephone number:
                <INPUT NAME="phone" TYPE="text"><BR>
                Please enter your E-mail address:
                <INPUT NAME="email" TYPE="text"><BR>

                 Please select the type of position in which you are interested:
                 <SELECT NAME="position">
                    <OPTION VALUE="a">Accounting</OPTION>
                    <OPTION VALUE="b">Bicycle repair</OPTION>
                    <OPTION VALUE="h">Human resources</OPTION>
                    <OPTION VALUE="m">Management</OPTION>
                    <OPTION VALUE="s">Sales</OPTION>
                 </SELECT><BR>

                 Please select the country in which you would like to work:
                 <SELECT NAME="country">
                    <OPTION VALUE="cn">Canada</OPTION>
                    <OPTION VALUE="cr">Costa Rica</OPTION>
                    <OPTION VALUE="de">Germany</OPTION>
                    <OPTION VALUE="uk">United Kingdom</OPTION>
                    <OPTION VALUE="us">United States</OPTION>
                 </SELECT><BR>

                 <INPUT NAME="avail" TYPE="checkbox"> Available immediately<BR>
                 <INPUT NAME="enter" TYPE="submit" VALUE="Enter">

            </FORM>
         </BODY>
      </HTML>




                                          TEAM FLY PRESENTS
 While this change does not affect the appearance or functionality of the application, it does make the code
 more manageable. In Chapter 6 "Statements", we will discuss how to use require() and include() to
 create a centralized script that can contain all of the constants needed by the entire application. For now, it
 is convenient enough just to define our constants near the top of the file that employs the constant.


Summary
 In this chapter we have looked in more detail at PHP variables and their data types. Constants and variables
 abstractly represent values. Constants are defined using the define() function. Once defined, a constant's
 value may not change. PHP has several built-in constants that contain information about the PHP script and
 its environment.

 The five data types in PHP are integer, double, string, array, and object. Boolean values are typically
 represented by zero or non-zero integers, though sometimes they are also represented by empty or non-
 empty strings. The type of a variable depends on the context in which it is used. PHP attempts to convert or
 juggle types as needed. To explicitly dictate a specific type, you can use casting, settype(), or the
 ...val() functions. The is...() functions can be used to determine a variable's current type.

 In the online job application form, we saw that the isset() function can be very useful for converting
 HTML checkbox data into boolean variables.




                                     TEAM FLY PRESENTS

				
DOCUMENT INFO
Shared By:
Categories:
Stats:
views:2
posted:5/8/2012
language:
pages:13
Description: php book,learn php online,complete php book