Variables and Types

only for RuBoard - do not distribute or recompile

Variables and Types

The concept of a variable is borrowed from algebraic notation. A variable always begins with a $, and what the variable represents (or contains) can be changed at any time during execution of the program. Variables are case sensitive. The variable $ Path is different from $path. Under certain conditions, variables exist before your program is executed. All other variables are named and created by you.

Variables take on characteristics known as types. These types include arrays, objects, strings, integers, real (also known as floating point), and resources. PHP will change the types of variables on-the-fly . Numbers become strings at will. Strings become numbers . Integers are changed to floating point. These changes are done behind the scenes, without any direct intervention on your part.

The following sections will give you a brief overview of the basic PHP types.

Arrays

When strings are used as subscripts in arrays, the result of an array lookup might not be obvious. If you have a two-dimensional array, it becomes even more of a problem.

Suppose you have an array that is describing dog types and names in two dimensions. The types are hound and lab. We have two hound dogs. The brown one is named Bill and the red one is named Hillary. We have two labs. The red one is named Lee and the black one is named Gore. There are two ways of setting up the arrays. The first is easiest to understand:

 $dog["hound"]["brown"]="Bill"; $dog["hound"]["red"]="Hillary"; $dog["lab"]["red"]="Lee"; $dog["lab"]["black"]="Gore"; 

The second way is equivalent, and is a bit faster to write:

 $dog = array (     "hound" => array (             "brown" => "Bill",             "red" => "Hillary"             ),     "lab" => array (             "red" = "Lee",             "black" = "Gore"             )     ); 

Either way of initializing the array works. In both cases, using the variable $dog [ "lab" ][ "red" ] will give you Lee. This can be a very powerful feature of PHP. It is very difficult to use unless you are using it with values that are placed in the PHP script directly. For example, you can't control how the word color is spelled. A British user will most likely spell it colour. This would cause an associative lookup based on the index "color" to fail.

Integers

In all computer languages I know of, and by definition in mathematics, an integer is a number without a decimal point. Integers can represent only whole numbers. An integer is assigned to a variable by using the equal sign:

 $a = 3; 

Floating Point

A number that has a fractional amount represented by numbers after a decimal point is called a floating point number. Floating point numbers can result from division or assignments. To assign a floating point number to a variable, use a decimal point in the number:

 $a = 1.345; 

Objects

You can use objects to group items together that are aspects of an idea or item. To illustrate this point, let's use a dog object. Nearly every dog has hair, most have tails , and all have ears. All dogs have a color. A dog will usually be able to bark. A dog can whine. All dogs eat. All dogs weigh a certain amount and can increase that weight by eating. They can lose weight by not eating .

To create this dog object, we will first describe a dog class. A class is simply an empty outline. When we use the class, we fill in the details, as shown in the following class:

NOTE

When you define variables in a class, you use the $ character with the variable name . When you use variables from a class, you do not use the $ character with the variable name. For example, if you have the variable $Color in a Dog object, to reference it you would use the following syntax:


 $Dog->Color = "Brown"; class DogClass {     var $color;     var $hair; // 1 (yes) or 0 (no)     var $bark; // 1 (yes) or 0 (no)     var $whine; //1 (yes) or 0 (no)     var $weight;     function eat() { $this->$weight = $this->$weight + 1; }     function dont_eat() { this->$weight = $this->$weight - 1; }     function bark() {         if ( $this->$bark )             return 1;         else             return 0;         }     function whine() {         if ( $this->$whine )             return 1;         else             return 0;         }     };     $Hairless = new DogClass;     $No = 0; $Yes = 1;     $Hairless->Hair = $No;     $Hairless->Bark = $Yes;     if ($Hairless->bark())         printf("Dog barked!\n");     else         printf("Dog is silent.\n");     if ($Hairless->Hair == $Yes)         print ("Dog has hair\n");     else         print ("Dog does not have hair\n"); 

Resource

A resource is a new type introduced in PHP 4. It is the identifier returned from calls that use system resources, such as a call to mysql_connect(). The variable is automatically assigned this type. This type has no affect on your PHP programming practices.

Strings

To put separate strings together, use a period ( . ). This process is called concatenation. Suppose you have "Old MacDonald" and "had a farm." To put these two strings together and print the result, you could do either one of the following:

 echo "Old MacDonald" . " " . "had a farm." $a = "Old MacDonald"; $a = $a . " " . "had a farm"; print($a); 

Note that I had to insert a space between the two strings to make them acceptable when concatenated . Otherwise it would have printed MacDonaldhad as opposed to MacDonald had

Also note that the concatenation operator works with variables as well as with strings.

You can also embed special characters in strings to force line breaks, tabs, and other special characters . To embed a character in a string, precede the character with a backslash (\). The backslash alerts PHP's parser to treat the next character as a representation of what you want done. The most-used list of embeddable characters is shown in the following table:

Escape Sequence Meaning
\\ backslash
\n newline
\" double quote
\' single quote
\r return
\$ dollar sign
\t tab

You can use the backslash for any character. If you do this, a warning will be put out at the highest warning level.

When PHP encounters a string with an arithmetic expression, it tries to convert the string to a value. For example, in the following, $a is a string and then changes into a number.

 $a = "3"; // $a is a string $b = $a +5; //$a is now the number 3, making $b equal to 8 $c = $a + 2 + "3 little pigs"; // $c is now equal to 8 

In the above statements, the Unix library function strtod () is used. To find out more about how the conversion of strings to numbers works, run man strtod in a terminal window.

Basically, any number in the beginning of a string is converted and the rest of the string is ignored. If the number in the string contains a . or the letters e or E it will become a double. If the string does not begin with a number, it will translate to a 0. You can use exponent notation to produce a number. This is sometimes known as scientific notation. The string 1e2 evaluates to 100 (1 followed by 2 zeros).

You must be careful when you use variables in PHP to avoid unexpected results. When the type conversions bite you, it is generally funny , unless the deadline is too close for comfort !

Type Casting and Conversion

You can force variables to be different types. This is called casting, and is useful for clarity. If you don't cast variables, they are automatically converted from one type to another on-the-fly.

Strings will be converted to numeric values. The conversion is based on the rules explained in the preceding section, strings.

You can change the type of a variable with settype(). To get the type of a variable, you can use gettype(). You can also use the functions is_array(), is_double(), is_long(), is_object(), and is_string().

To temporarily change the type of a variable, use a cast. In the following examples, the number 12 is changed to a floating point number, and the floating point number 33.45 is changed to an integer:

 $double = (float) 10; // $double now is 10.0 $smallint = (int) 33.45; // $smallint is now 33 

The type casts allowed are shown in the following table. Alternative casts that have the same effect are shown separated by a comma:

Cast Effect on Variable
(array) changes to an array
(double), (float), (real) changes to a floating point number
(int), (integer) changes to an integer
(object) changes to an object
(string) changes to a string

Predefined Variables

Some variables are in existence before your PHP code is executed. These variables are environment variables, GET and POST variables, and cookies. These variables are used like any other PHP variables.

Cookies are sent from the client (the Web browser) and are available as PHP variables. The variable name is the same name as the cookie, with a $ prepended. Cookies that you have set using setcookie() will be returned by the browser in all following page requests .

Variable Scoping

The concept of variable scoping can be confusing at first. Basically, it answers the question "When is the variable available for me to use?" The availability of a variable is further complicated by the fact that you are allowed to create PHP variables as needed.

The basic rule is this: Variables defined outside of functions are not visible within functions unless the variable is preceded by the word global anywhere before use of the variable.

In the following example, the variables $one and $two are visible in the function. The variable $three is a new variable within the function, and changes to it do not affect the $three variable outside the function:

 <?php $one = 1; $two = 2; $three = 3; function foo() {   global $one, $two;   static $three;   $three = $one *2 + $two * 2; } ?> 

The reverse concept is also true: Variables defined within a function are not visible to the rest of the program. Variables defined within a function also cease to exist when the function is exited, in most cases. If you put the word static in front of a function variable, it will continue to exist when you leave the function. When you call the function again, the variable can be used, and will have the last value put into it.

Variable Variables

A variable that is a string can be used as a variable name by using two $ symbols in a row. The content of the variable is matched against an existing variable if one exists. If one does not exist, a new variable is created. To illustrate, the following code

 $me = "me, you dummie!";   $who =  "me";   printf ("who? $me \n<p>");   $$who = "george!";   printf ("who? $me \n"); 

will print the following:

 who? me, you dummie!        who? George! 

When using arrays as variable variables, you must use brackets to avoid ambiguity. Please note that you are not limited to using brackets for arrays. You can use them for all variable variables.

To use the contents of $a[1] as the variable name, you would write ${$a[1]}. To use the contents of $a as the array name, with an index of 1, you would write ${$a}[1].

You can also use the PHP defined $ GLOBALS array for accessing variable variables. It is an associative array, with the name of the variable being the key. To access the contents of $a[1] using the $GLOBALS array, you would write $GLOBALS[$a[1]], and to access the $who variable, you would write $GLOBALS["who"].

External Variables

You can create or modify external environment variables by using the putenv() function. To create or modify cookies, use the setcookie() function. You can modify variables passed to you from HTML forms or the environment using a direct assignment. However, this only modifies the variable during execution of your PHP script.

HTML Form-Provided Variables

When your PHP Web page is called using a POST or GET method, the variable name is specified using name=. The variable contents are entered by the user. In the following example, a variable called $item is handed to the PHP

script on the Web page. The $item variable can be used like any other variable.

 <form action="postexample.hp3" method="post"> Item:<input type="text" name="item"><p> <input type="submit"> </form> 

In this case, you can change the value of $item during the execution of your script. If you do, you will not be able to get the original value of $item back. Be careful!

NOTE

In PHP 4, you can turn off this behavior by turning off register_globals in the php.ini file. If you do this, turn on access to external variables using the track_vars configuration directive in the php.ini file. If you do this, you then use $HTTP_POST_VARS["varname"], $HTTP_GET_VARS["varname"], $HTTP_ COOKIE_VARS["varname"], $HTTP_ENV_VARS["varname"], or $HTTP_SERVER_ VARS["varname"] to retrieve the variables.


Environment Variables

Environment variables were discussed in part in the section "Predefined Variables" and the introduction to this section, "External Variables." These variables are immediately usable within a PHP script.

Direct modification of environment variables within the PHP code might not give you the results you are after. If other variables have the same name as environment variables, they will override the environment variable's current setting. For that reason, it is best to use getenv() function to get the value of an environment variable. Changes to environment variables with the putenv() function might or might not carry forward to other PHP scripts that are executed. It is best to assume that changes to environment variables are temporary, unless you do a lot of testing to prove otherwise.

only for RuBoard - do not distribute or recompile


MySQL and PHP From Scratch
MySQL & PHP From Scratch
ISBN: 0789724405
EAN: 2147483647
Year: 1999
Pages: 93
Authors: Wade Maxfield

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net