Index
    Preface
      What This Book Is About
      What You Need to Know
      How This Book Is Organized
      How to Use This Book
      Conventions Used in This Book
      Using Code Examples
      How to Contact Us
      Web Site and Code Examples
      Acknowledgments
      Chapter 1.  Database Applications and the Web
      Section 1.1.  The Web
      Section 1.2.  Three-Tier Architectures
      Chapter 2.  The PHP Scripting Language
      Section 2.1.  Introducing PHP
      Section 2.2.  Conditions and Branches
      Section 2.3.  Loops
      Section 2.4.  Functions
      Section 2.5.  Working with Types
      Section 2.6.  User-Defined Functions
      Section 2.7.  A Working Example
      Chapter 3.  Arrays, Strings, and Advanced Data Manipulation in PHP
      Section 3.1.  Arrays
      Section 3.2.  Strings
      Section 3.3.  Regular Expressions
      Section 3.4.  Dates and Times
      Section 3.5.  Integers and Floats
      Chapter 4.  Introduction to Object-Oriented Programming with PHP 5
      Section 4.1.  Classes and Objects
      Section 4.2.  Inheritance
      Section 4.3.  Throwing and Catching Exceptions
      Chapter 5.  SQL and MySQL
      Section 5.1.  Database Basics
      Section 5.2.  MySQL Command Interpreter
      Section 5.3.  Managing Databases and Tables
      Section 5.4.  Inserting, Updating, and Deleting Data
      Section 5.5.  Querying with SQL SELECT
      Section 5.6.  Join Queries
      Section 5.7.  Case Study: Adding a New Wine
      Chapter 6.  Querying Web Databases
      Section 6.1.  Querying a MySQL Database Using PHP
      Section 6.2.  Processing User Input
      Section 6.3.  MySQL Function Reference
      Chapter 7.  PEAR
      Section 7.1.  Overview
      Section 7.2.  Core Components
      Section 7.3.  Packages
      Chapter 8.  Writing to Web Databases
      Section 8.1.  Database Inserts, Updates, and Deletes
      Section 8.2.  Issues in Writing Data to Databases
      Chapter 9.  Validation with PHP and JavaScript
      Section 9.1.  Validation and Error Reporting Principles
      Section 9.2.  Server-Side Validation with PHP
      Section 9.3.  JavaScript and Client-Side Validation
      Chapter 10.  Sessions
      Section 10.1.  Introducing Session Management
      Section 10.2.  PHP Session Management
      Section 10.3.  Case Study: Using Sessions in Validation
      Section 10.4.  When to Use Sessions
      Section 10.5.  PHP Session API and Configuration
      Chapter 11.  Authentication and Security
      Section 11.1.  HTTP Authentication
      Section 11.2.  HTTP Authentication with PHP
      Section 11.3.  Form-Based Authentication
      Section 11.4.  Protecting Data on the Web
      Chapter 12.  Errors, Debugging, and Deployment
      Section 12.1.  Errors
      Section 12.2.  Common Programming Errors
      Section 12.3.  Custom Error Handlers
      Chapter 13.  Reporting
      Section 13.1.  Creating a Report
      Section 13.2.  Producing PDF
      Section 13.3.  PDF-PHP Reference
      Chapter 14.  Advanced Features of Object-Oriented Programming in PHP 5
      Section 14.1.  Working with Class Hierarchies
      Section 14.2.  Class Type Hints
      Section 14.3.  Abstract Classes and Interfaces
      Section 14.4.  Freight Calculator Example
      Chapter 15.  Advanced SQL
      Section 15.1.  Exploring with SHOW
      Section 15.2.  Advanced Querying
      Section 15.3.  Manipulating Data and Databases
      Section 15.4.  Functions
      Section 15.5.  Automating Querying
      Section 15.6.  Table Types
      Section 15.7.  Backup and Recovery
      Section 15.8.  Managing Users and Privileges
      Section 15.9.  Tuning MySQL
      Chapter 16.  Hugh and Dave's Online Wines:A Case Study
      Section 16.1.  Functional and System Requirements
      Section 16.2.  Application Overview
      Section 16.3.  Common Components
      Chapter 17.  Managing Customers
      Section 17.1.  Code Overview
      Section 17.2.  Customer Validation
      Section 17.3.  The Customer Form
      Chapter 18.  The Shopping Cart
      Section 18.1.  Code Overview
      Section 18.2.  The Winestore Home Page
      Section 18.3.  The Shopping Cart Implementation
      Chapter 19.  Ordering and Shipping at the Online Winestore
      Section 19.1.  Code Overview
      Section 19.2.  Credit Card and Shipping Instructions
      Section 19.3.  Finalizing Orders
      Section 19.4.  HTML and Email Receipts
      Chapter 20.  Searching and Authentication in the Online Winestore
      Section 20.1.  Code Overview
      Section 20.2.  Searching and Browsing
      Section 20.3.  Authentication
      Appendix A.  Linux Installation Guide
      Section A.1.  Finding Out What's Installed
      Section A.2.  Installation Overview
      Section A.3.  Installing MySQL
      Section A.4.  Installing Apache
      Section A.5.  Installing PHP
      Section A.6.  What's Needed for This Book
      Appendix B.  Microsoft Windows Installation Guide
      Section B.1.  Installation Overview
      Section B.2.  Installing with EasyPHP
      Section B.3.  What's Needed for This Book
      Appendix C.  Mac OS X Installation Guide
      Section C.1.  Getting Started
      Section C.2.  Installing MySQL
      Section C.3.  Setting Up Apache and PHP
      Section C.4.  What's Needed for This Book
      Appendix D.  Web Protocols
      Section D.1.  Network Basics
      Section D.2.  Hypertext Transfer Protocol
      Appendix E.  Modeling and Designing Relational Databases
      Section E.1.  The Relational Model
      Section E.2.  Entity-Relationship Modeling
      Appendix F.  Managing Sessions in theDatabase Tier
      Section F.1.  Using a Database to Keep State
      Section F.2.  PHP Session Management
      Section F.3.  MySQL Session Store
      Appendix G.  Resources
      Section G.1.  Client Tier Resources
      Section G.2.  Middle-Tier Resources
      Section G.3.  Database Tier Resources
      Section G.4.  Security and Cryptography Resources
      Appendix H.  The Improved MySQL Library
      Section H.1.  New Features
      Section H.2.  Getting Started
      Section H.3.  Using the New Features
    Colophon
    Copyright



 

Previous Section  < Day Day Up >  Next Section

2.5 Working with Types

PHP is a loosely typed language, allowing variables and function parameters to be set to any type of data. Similarly, functions can return different data types in different circumstances.

In the last section, we introduced the function prototype as a way of describing the type of parameters that functions are designed to work with and the types of data that are returned. Since PHP is loosely typed, PHP can't enforce these types as strongly typed languages do. To illustrate this, the PHP library function strtoupper( ) is designed to operate on strings, but can be called with an integer parameter:

$var = 42;



print strtoupper($var); // prints the string "42"

When functions are designed to work with different data types, prototypes describe parameters and return values as mixed. Other functions may not work as expected, or may not work at all, when the wrong type of data is used.

2.5.1 Type Conversion

PHP provides several mechanisms to allow variables of one type to be considered as another type. Variables can be explicitly converted to another type with the following functions:

string strval(mixed variable)
integer intval(mixed variable [, integer base])
float floatval(mixed variable)

The functions convert the variable into a string, integer, or float respectively. The intval( ) function also allows an optional base that determines how the variable is interpreted.

$year = 2003;



// Sets $yearString to the string value "2003"

$yearString = strval($year);



$var = "abc";



// sets $value to the integer 0

$value = intval($var);



// sets $count to the integer value 2748 - the 

// integer value of "abc" as a hexadecimal number

$count = intval($var, 16);

Because the string "abc" doesn't look anything like an integer, the first call to the intval( ) function sets $value to zero.

PHP also supports type conversion with type-casting operators in much the same way as C, to allow the type of an expression to be changed. When you place the type name in parentheses in front of a variable, PHP converts the value to the desired type:

// cast to an integer: the following are equivalent

$int = (int) $var;

$int = (integer) $var;

$int = intval($var);



// cast to a Boolean

$bool = (bool) $var;

$bool = (boolean) $var;

// cast to a float

$float = (float) $var;

$float = floatval($var);



// cast to a string

$str = (string) $var;

$str = strval($var);



// cast to an array

$arr = (array) $var;



// cast to an object

$obj = (object) $var;

In the previous example, type casting, and calls to the strval( ), intval( ), and floatval( ) functions don't change the value or type of the variable $var. The settype( ) function actually modifies the variable that it is called with. For example:

boolean settype(mixed variable, string type)

settype( ) explicitly sets the type of variable to type, where type is one of array, boolean, float, integer, object, or string.

// cast to an integer: the following are equivalent

$var = 39;



// $var is now a string

settype($var, "string");

The rules for converting types are mostly common sense, but some conversions may not appear so straightforward. Table 2-1 shows how various values of $var are converted using the (int), (bool), (string), and (float) casting operators.

Table 2-1. Examples of type conversion in PHP

Value of $var

(int) $var

(bool) $var

(string) $var

(float) $var

null

0

false

""

0

true

1

true

"1"

1

false

0

false

""

0

0

0

false

"0"

0

3.8

3

true

"3.8"

3.8

"0"

0

false

"0"

0

"10"

10

true

"10"

10

"6 feet"

6

true

"6 feet"

6

"foo"

0

true

"foo"

0


2.5.2 Automatic Type Conversion

Automatic type conversion occurs when two differently typed variables are combined in an expression or when a variable is passed as an argument to a library function that expects a different type. When a variable of one type is used as if it were another type, PHP automatically converts the variable to a value of the required type. The same rules are used for automatic type conversion as demonstrated previously in Table 2-1.

Some simple examples show what happens when strings are added to integers and floats, and when strings and integers are concatenated:

// $var is set as an integer = 115

$var = "100" + 15;



// $var is set as a float = 115.0

$var = "100" + 15.0;



// $var is set as a string = "39 Steps"

$var = 39 . " Steps";

Not all type conversions are so obvious and can be the cause of hard-to-find bugs:

// $var is set as an integer = 39

$var = 39 + " Steps";

// $var is an integer = 42

$var = "3 blind mice" + 39;



// $var is a float, but what does it mean?

$var = "test" * 4 + 3.14159;

Automatic type conversion can change the type of a variable. Consider the following example:

$var = "1";   // $var is a string == "1"

$var += 2;    // $var is now an integer == 3

$var /= 2;    // $var is now a float == 1.5

$var *= 2;    // $var is still a float == 3

Care must be taken when interpreting non-Boolean values as Boolean. Many library functions in PHP return values of different types in different circumstances. For example, many functions return the Boolean value false if a valid result could not be determined. If the function is successful, they return the valid integer, string, or compound type. However, a valid return value of 0, 0.0, "0", an empty string, null, or an empty array is also equal to the Boolean value false and can be misinterpreted as failure.

The solution is to test the type of the variable using the functions described in the next section.


2.5.3 Examining Variable Type and Content

Because PHP is flexible with types, it provides the following functions that can check a variable's type:

boolean is_int(mixed variable)
boolean is_float(mixed variable)
boolean is_bool(mixed variable)
boolean is_string(mixed variable)
boolean is_array(mixed variable)
boolean is_object(mixed variable)

All the functions return a Boolean value of true or false depending on whether the type of variable matches the variable type that forms the name of the function. For example, is_float( ) evaluates to true in the following code:

$test = 13.0;



// prints "Variable is a float"

if (is_float($test))

    print "Variable is a float";

2.5.3.1 Is-identical and is-not-identical operators

While the PHP equals operator == tests the values of two variables, it doesn't test the variables types. Consider the comparisons of string and integer variables:

$stringVar = "10 reasons to test variable type";

$integerVar = 10;



// Prints "Variables have the same value"

if ($stringVar == $integerVar)

    print "Variables have the same value";

Because of PHP's automatic type conversion, $stringVar == $integerVar evaluates to true. PHP provides the is-identical operator === that tests not only values, but types. In the fragment below, the expression $stringVar === $integerVar evaluates to false:

$stringVar = "10 reasons to test variable type";

$integerVar = 10;



// Does not print anything

if ($stringVar === $integerVar)

    print "Variables have the same value and type";

PHP also provides the is-not-identical operator, !== , that returns true if the value or type of two expressions are different.

2.5.3.2 Debugging with gettype( ), print_r( ), and var_dump( )

PHP provides the gettype( ) , print_r( ), and var_dump( ) functions, which print the type and value of an expression in a human-readable form:

string gettype(mixed expression)
print_r(mixed expression)
var_dump(mixed expression [, mixed expression ...])

These functions are useful for debugging a script, especially when dealing with arrays or objects. To test the value and type of $variable at some point in the script, the following code can be used:

$variable = "3 Blind mice" + 39;

var_dump($variable);

This prints:

int(42)

While the var_dump( ) function allows multiple variables to be tested in one call, and provides information about the size of the variable contents, print_r( ) provides a more concise representation of arrays and objects, and will prove useful later when we start to use those variables.

The gettype( ) function simply returns the type name for an expression:

$variable = "3 Blind mice" + 39;



// prints: "integer"

print(gettype($variable));

The name that gettype( ) returns should only be used for information and not to programmatically test the type of a variable as the output is not guaranteed to remain stable with future PHP releases. To programmatically test a variable type, you should use the is_int( ), is_float( ), is_bool( ), is_string( ), is_array( ), or is_object( ) functions described earlier.

The gettype( ), print_r( ), and var_dump( ) functions can be used on variables and expressions of any type, and we use them throughout the book to help illustrate the results of our examples.

2.5.3.3 Testing, setting, and unsetting variables

During the running of a PHP script, a variable may be in an unset state or may not yet be defined. PHP provides the isset( ) function and the empty( ) language construct to test the state of variables:

boolean isset(mixed var)
boolean empty(mixed var)

isset( ) tests if a variable has been set with a non-null value, while empty( ) tests if a variable is equal to false. The two are illustrated by the following code:

$var = 0;



// prints: "Variable is Set"

if (isset($var)) print "Variable is Set";



// prints: "Variable is Empty"

if (empty($var)) print "Variable is Empty";



$var = "test";



// prints: "Variable is Set"

if (isset($var)) print "Variable is Set";



// Doesn't print

if (empty($var)) print "Variable is Empty";

A variable can be explicitly destroyed using unset( ) :

unset(mixed var [, mixed var [, ...]])

After the call to unset in the following example, $var is no longer defined:

$var = "foo";



// Later in the script

unset($var);



// Does not print

if (isset($var)) print "Variable is Set";

Table 2-2 show the return values for isset($var) and empty($var)when the variable $var is tested. Some of the results may be unexpected: when $var is set to "0," empty( ) returns true.

Table 2-2. Expression values

State of the variable $var

isset($var)

empty($var)

unset $var;

false

true

$var = null;

false

true

$var = 0;

true

true

$var = true;

true

false

$var = false;

true

true

$var = "0";

true

true

$var = "";

true

true

$var = "foo";

true

false

$var = array( );

true

true


A variable is always set when it is assigned a value—with the exception of a null assignment—and isset( ) returns true. The empty( ) function tests the Boolean value of the variable and returns true if the variable is false. The statement

$result = empty($var);

is equivalent to

$result = not (boolean) $var;

However, PHP issues a warning when a cast operator is used on an unset variable, whereas empty( ) doesn't.

    Previous Section  < Day Day Up >  Next Section







    Copyright © 2010 | Domen maybe sale - bye this domen