Chapter 1: Introducing PHP and XML


 Download CD Content

PHP is a server-side HTML embedded scripting language that you can use to create dynamic Web pages. It includes predefined functions that create, open , read, write, and close files stored on the server. You can create XML-based Web applications using PHP.

Some browsers such as Netscape Communicator 4.x series do not contain Some browsers such as Netscape Communicator 4.x series do not contain (XML) parser. Hypertext Preprocessor (PHP) overcomes this problem by supporting XML parsing. PHP provides a Document Object Model to access XML elements, an XML extension, and an eXtensible Stylesheet Language (XSL) processor to support XML parsing.

This chapter introduces PHP fundamentals. It describes data types, variables , operators, control structures, functions, and error handling in PHP. It also explains how to create classes in PHP and use PHP to work with files. This chapter also introduces XML fundamentals, such as Document Type Declaration (DTD), namespaces, and XML schemas.

Introducing PHP

PHP, developed using the C language, is specifically designed to work with databases. It provides a set of Application Programming Interfaces (APIs) to connect to different types of database servers, such as MySQL, SQL Server, and Oracle. PHP scripts are portable because they can run on various operating systems, such as Linux and Windows.

When a user accesses a Web page created using a PHP script, the Web server contacts the PHP engine to load, compile, and run the PHP script. Using PHP script, you can work with different data types, variables, constants, operators, functions, classes, objects, and files.

Data Types, Variables, and Constants

A variable is a container that stores variable data, such as number, character, and date.

PHP provides data types that specify type of values a variable can contain. For example, a data type defines that a variable, num, can contain only numbers . The data types that PHP supports are:

  • Integer: Represents whole numbers. In PHP, integer variables can store values between -2, 147, 483, 648 and +2, 147, 483, 647. For example, in $a=5, $a is an integer variable that is assigned the value, 5.

  • Float: Stores decimal values. PHP lets you store floating numbers in both normal and scientific notation. Scientific notation is a shorthand way of writing very large or very small numbers. A number expressed in scientific notation is expressed as a decimal number between 1 and 10, followed by e or E, multiplied by a power of 10. For example, in $a=5.2E2, $a is a float variable created using scientific notation and contains the value 520.

  • Boolean: Stores the values, true or false. For example, in $a=true, $a is a Boolean variable that is assigned the value, true.

  • String: Stores string information enclosed within double quotes. For example, in $a="Angela Jones", $a represents a string variable that contains the string, Angela Jones.

  • Array: Stores elements in the form of key/value pairs. The key values start with zero.

  • Object: Stores data and provides functions to process the data.

  • Resource: Stores references to functions or other resources external to PHP.

  • Null: Represents an undefined value.

Note  

In PHP, you can declare variables without specifying its data type.

Operators

PHP provides several operators, such as the arithmetic, comparison, logical, and assignment operators. You can perform arithmetic operations on variables and constants using the arithmetic operators of PHP.

Table 1-1 lists the arithmetic operators:

Table 1-1: Arithmetic Operators

Name

Symbol

Description

Addition

+

Adds two numbers.

Subtraction

-

Subtracts two numbers.

Multiplication

*

Calculates the product of two numbers.

Division

/

Divides two numbers.

Modulus

%

Calculates the remainder when one number is divided by the other.

Increment

++

Increments the number, to which it is applied, by 1.

Decrement

--

Decrements the number, to which it is applied, by 1.

PHP also supports the comparison operators to compare two or more values, to determine which value is greater, lesser, equal, or not equal to the other.

Table 1-2 lists the comparison operators in PHP:

Table 1-2: Comparison Operators

Name

Symbol

Description

Greater than

>

Returns true if the value on the left hand side of the operator is greater than the value on the right hand side.

Less than

<

Returns true if the value on the left hand side of the operator is less than the value on the right hand side.

Greater than equal to

>=

Returns true if the value on the left hand side of the operator is greater than or equal to the value on the right hand side.

Less than equal to

<=

Returns true if the value on the left hand side of the operator is less than or equal to the value on the right hand side.

Equal to

==

Returns true if the two values being compared are equal.

Not Equal to

!=

Returns true if the two values being compared are not equal.

PHP supports the logical operators that you can use to create Boolean expressions. Boolean expressions either return true or false.

Table 1-3 lists the operators that PHP supports:

Table 1-3: Logical Operators in PHP

Name

Symbol

Description

And

&&

Returns true if both the conditions placed on the left and right of the operator are true.

Or

Returns true if either of the conditions placed on the left and right of the operator is true.

Not

!

Returns true if the condition specified is not true.

You can use assignment operators in PHP to assign values to the variables. PHP also supports compound operators that perform the functions of the arithmetic and assignment operators in a single statement.

Table 1-4 lists the assignment and compound operators in PHP:

Table 1-4: Assignment and Compound Operators

Operator

Implementation

Description

=

a =5

Assign the value, 5, to the variable, a.

+=

a+=5

Adds the value, 5, to the original value of the variable, a, and then assigns the sum to the variable, a. This is equivalent to a=a+5.

-=

a-=5

Subtracts the value, 5, from the original value of the variable, a, and then assigns the difference to the variable, a. This is equivalent to a=a-5.

*=

a*=5

Multiplies the value, 5, with the original value of the variable, a, and then assigns the product to the variable, a. This is equivalent to a=a*5.

/=

a/=5

Divides the value in the variable, a, by 5 and then assigns the result to the variable, a. This is equivalent to a=a/5.

%=

a%=5

Divides the value in the variable, a, by 5 and then assigns the remainder to the variable, a. This is equivalent to a=a%5.

Control Structures

You can control the flow of execution of a PHP script using control structures. Two types of control structures are conditional statements and loops .

Conditional statements support unidirectional flow of control in processing a script. The conditional statement returns the true or false value after evaluating a condition, and then transfers the control to a section of the script, depending on the value returned after evaluating the condition. In PHP, two types of conditional statements are if else and switch case statement.

The if else conditional statement is divided into two parts , the if statement and the else statement. The if statement evaluates a condition and returns the value, true, or false. The if statement is followed by the PHP script enclosed in braces. This script runs if the value returned is true. The else statement contains the PHP script that runs if the condition evaluated is false. The syntax of the if else conditional statement is:

 if(condition) {statements to run if condition is true} else {statements to run if condition is false} 

In the above syntax, the condition parameter is an expression that is evaluated to return true or false. To run a single PHP programming statement, you do not need the braces.

Listing 1-1 shows how to use the if condition to display the maximum of three numbers:

Listing 1-1: Maximum of Three Numbers
start example
 <?php $x=10; $y=20; $z=30; if($x > $y) {    if($x > $z)    {       echo("The maximum number is ");       echo("$x<p>");    }    else    {       echo("The maximum number is ");       echo("$z<p>");    } } else {    if($y > $z)    {       echo("The maximum number is ");       echo("$y<p>");    }    else    {       echo("The maximum number is ");       echo("$z<p>");    } } ?> 
end example
 

The above listing shows the use of the if else condition statements to create a PHP script. The if condition compares the values of the two variables, and then controls the flow of execution of the script, depending on whether the condition returns true or false.

Create a new folder, PHP_XML, in the var/www/html directory of the Apache Web server. Save the above listing as MaxThree.php in the PHP_XML folder.

Figure 1-1 shows the output when PHP_XML is viewed in the Konqueror Web browser:

click to expand: this figure shows that the maximum number, out of the given numbers, is 30.
Figure 1-1: Viewing MaxThree.php

The switch case statement is another conditional statement that controls the flow of execution of a script. The switch statement compares a single variable with several values. To specify the values to which a variable is compared, you use the case statement with the switch statement. The syntax of the switch case conditional statement is:

 switch($Variable) {    case 1:    //statements to be run if case is true;    break;    case 2:    //statements to be run if case is true;    break;    default:    //statements to be run if all cases are false; } 

In the above syntax, the break statement is used within a case statement to identify the end of a case. The default statement is used in the switch case condition to specify the PHP statements that are run if all the cases are false.

Listing 1-2 shows how to use the switch case conditional statement to perform simple arithmetic operations:

Listing 1-2: Using the switch case Conditional Statement
start example
 <?php //Initializing variables $a = 10; $b = 5; echo("1. Addition <br>"); echo("2. Subtraction <br>"); echo("3. Multiplication <br>"); echo("4. Division <br>"); $ch=3; switch ($ch) {    case 1:    $d=$a+$b;    echo("The sum of the two numbers is $d");    break;    case 2:    $d=$a-$b;    echo("The difference of the two numbers is $d");    break;    case 3:    $d=$a*$b;    echo("The product of the two numbers is $d");    break;    case 4:    $d=$a/$b;    echo("The quotient of the two numbers is $d");    break;    default:    echo("Incorrect Option");    break; } ?> 
end example
 

The above listing shows how to use the switch case statement. The switch case statements:

  • Display the sum of two numbers, if the variable, $ch, is assigned the value, 1.

  • Display the difference of the two numbers, if the variable, $ch, is assigned the value, 2.

  • Display the product of the two numbers, if the variable, $ch, is assigned the value, 3.

  • Display the quotient of the two numbers, if the variable, $ch, is assigned the value, 4.

  • Assign the variable, $ch, the value 3 to multiply two numbers.

Because value, 3, is assigned to the variable $ch, Listing 1-2 displays the product of the two numbers.

Save the above listing as Switch.php in the PHP_XML folder.

Figure 1-2 shows the output when the Switch.php file is viewed in the Konqueror Web browser:

click to expand: this figure shows that the product of the two numbers is 50.
Figure 1-2: Viewing Switch.php

Loops support the repetitive execution of a set of statements in the PHP script. The loop statements evaluate a Boolean condition on each iteration that returns true or false after evaluating a condition. A set of statements enclosed within a loop is processed if the condition evaluates to true. The different types of loop statements in PHP are:

  • while loop

  • do while loop

  • for loop

  • foreach loop

The while loop evaluates a condition as true or false. The variable that you use in the while condition needs to be initialized before the while loop. The value of the variable is changed as the while loop executes. The execution of the while loop terminates as soon as the specified condition becomes false. The syntax for using the while loop is:

 $var=initialization while(condition checking the value of the variable, $var) {     //statements to run;    //increment/decrement var } 

In the above syntax, the variable, $var, is initialized outside the while loop. The while loop evaluates the condition as true or false and then runs the statements within the loop, if the condition is true. The increment or decrement operation within the loop modifies the value of the variable used in the condition till the condition becomes false.

Listing 1-3 shows how to use the while loop to display even numbers from 2 to 30:

Listing 1-3: Using the while Loop
start example
 <?php $a=2; echo("<p>Even Numbers from 2 to 30<p>"); while ($a <=30) {    echo("$a <br>");    $a=$a+2; } ?> 
end example
 

The above listing shows how to use the while loop to display even numbers. In the above listing:

  • The variable, a, is initialized to value 2.

  • The while condition compares whether the value of the variable is less than or equal to 30, and returns true or false.

  • The increment operation adds 2 to the value of the variable, a, every time the loop runs.

Save the above listing as While.php in the PHP_XML folder.

Figure 1-3 shows the output when While.php is viewed in the Konqueror Web browser:

click to expand: this figure shows all the even numbers from 2 to 30.
Figure 1-3: Viewing While.php

In the do-while loop, unlike in the while loop, the condition is evaluated after executing the statements once in the do-while loop. The syntax of the do-while loop is:

 $var = initialization do {    //statements to run;    //increment/decrement var; } while(condition); 

In the above syntax, the variable is initialized outside the do-while loop. The do keyword indicates the beginning of the do-while loop. The while condition is specified at the end of the listing and ends with the semicolon symbol.

In a for loop statement, you can initialize a counter variable, specify the condition, and specify the increment or decrement condition in the loop statement together. The syntax of the for loop statement is:

 for(initialization;condition;increment_decrement_operation) 

{

 //Statements to run; } 

You can embed one for loop statement inside another.

Listing 1-4 shows how to use the for loop to display prime numbers:

Listing 1-4: Using the for Loop
start example
 <?php echo("Prime Numbers between 1 and 30<p>"); //For loop from 1 to 30 for($var=1;$var<30;$var++) {    $ctr=0;    for($k=2;$k<=$var/2;$k++)    {       $d=$var%$k;       if ($d == 0)       {          $ctr=1;          break;       }    }    if($ctr==0)    {       echo($var);       echo("<br>");    } } ?> 
end example
 

The above listing shows how to use the for loop to display prime numbers from 1 to 30. The PHP script uses nested for loops to display the value of the variable, $var. Save the above listing as For.php in the PHP_XML folder.

Figure 1-4 shows the output when For.php is viewed in the Konqueror Web browser:

click to expand: this figure shows all the prime numbers between 1 and 30.
Figure 1-4: Viewing For.php

Functions

A function is a set of instructions that is grouped under a name. Instead of repeating all the instruction steps every time you use them in the script, you can call the function to run the same set of instructions again. PHP provides a set of built-in functions to use in the PHP scripts. In addition to the built-in functions, you can also define certain functions called user-defined functions. The syntax to define a function in PHP is:

 <?php function funcname($arg1,$arg2) {//Statements to run; return $val;} ?> 

In the above syntax:

  • The function keyword defines a PHP function.

  • The funcname parameter defines the name of the function.

  • The $arg1 and $arg2 parameters indicate the arguments that the function can receive.

  • The return keyword returns a value from the function.

Listing 1-5 shows how to define and call a function in PHP:

Listing 1-5: User-Defined Function in PHP
start example
 <?php echo("<center><h2>Displaying even numbers</h2></center><p><p>"); function displayeven() {    $ctr=0;    echo("<font size=4>");    for($i=2;$i<=100;$i+=2)    {       echo("$i &nbsp;&nbsp;&nbsp;");       $ctr++;       if($ctr%10==0)       {          echo("<p>");       }    }    echo("</font>"); } echo("<center><h2>Displaying even numbers</h2></center><p><p>"); displayeven(); ?> 
end example
 

The above listing creates a function, displayeven() that displays even numbers greater than zero and less than or equal to 100.

Save the above listing as Functions.php in the PHP_XML folder.

Figure 1-5 shows the output when Function.php is viewed in the Web browser:

click to expand: this figure shows all the even numbers between 1 and 100.
Figure 1-5: Viewing Functions.php

You can create nested functions, where you can define a function within another function. For example, in an application where you need to generate all prime numbers between two numbers entered by the end user, the outer function accepts the end user input and the inner function generates prime numbers. The inner function is a nested function, and is called only after calling the outer function. The syntax for creating a nested function is:

 <?php function outer_function($arg1) {    //Statements to run for outer_function();    function inner_innerfunction($arg2, $arg3)    {       //Statements to run for inner_function()    }    outer_function();    inner_function(); } 

The above syntax shows how to create two functions, inner_function() and outer_function(). The inner_function() function is nested within the outer_function() function. The outer_function() function is called before the inner_function() function.

Note  

In a nested function definition, calling the inner function before the outer function results in an error.

Listing 1-6 shows how to use nested functions in PHP:

Listing 1-6: Using Nested PHP Functions
start example
 <?php function msg() {    echo("<center><h2>Displaying even    numbers</h2></center><p><p>");    function displayeven()    {       $ctr=0;       echo("<font size=4>");       for($i=2;$i<=100;$i+=2)       {          echo("$i &nbsp;&nbsp;&nbsp;");          $ctr++;          if($ctr%10==0)          {             echo("<p>");          }       }       echo("</font>");    } } msg(); displayeven(); ?> 
end example
 

The above listing shows how to use nested functions. In the above listing:

  • the displayeven() function is nested within the msg() function.

  • the msg() function displays a message, Displaying even Numbers.

  • the displayeven() function displays even numbers between 1 and 100.

  • the displayeven() function is called only after calling the msg() function.

Save the above listing as NestedFunction.php in the PHP_XML folder.

Figure 1-6 shows the output when NestedFunction.php is viewed in the Web browser:

click to expand: this figure shows even numbers between 2 and 100, displayed using the nested functions.
Figure 1-6: Viewing NestedFunction.php

Error Handling

An error represents an incorrect result, produced either because of wrong logic, such as division by zero, or improper working of other applications, such as the database server that the PHP script is using. PHP displays the error message either on the Web page, or in the error log files. The error message contains information about the nature and source of an error.

PHP has built-in support for error handling and classifies errors according to the following error types:

  • E_NOTICE: Represents minor nonfatal errors that you use to identify the possible bugs within the PHP script. These errors do not stop the execution of the PHP script. E_NOTICE errors are not displayed on the Web page by default.

  • E_WARNING: Represents nonfatal runtime errors that do not stop the execution of the PHP scripts. The errors generated by external applications, such as database servers, are represented by E_WARNING errors. These errors differ from E_NOTICE as the latter is associated with identifying bugs within the PHP script whereas the former is generated by external applications.

  • E_ERROR: Represents fatal errors that stop the execution of the PHP script.

  • E_PARSE: Represents parsing errors generated by the PHP parser, which indicate syntax error in the PHP script.

In addition to the standard errors, PHP also provides custom error types that PHP scripts can generate using the trigger_error() function. The custom error types are:

  • E_USER_NOTICE: Represents the customized or user-defined version of the E_NOTICE error type.

  • E_USER_WARNING: Represents the customized or user-defined version of the E_WARNING error type.

  • E_USER_ERROR: Represents the customized or user-defined version of the E_ERROR error type.

PHP provides built-in error handling functions that handle errors of different types, such as E_ERROR, E_WARNING. Some error handling functions are:

  • int error_reporting ( int err_type): Specifies what error types should be displayed on the Web page. The parameter, err_type, takes either integers or named constants to represent the error type. Table 1-5 shows the named constants and their equivalent integer values:

    Table 1-5: Named Constants and Equivalent Integer Values

    Named Constant

    Integer Value

    E_ERROR

    1

    E_WARNING

    2

    E_PARSE

    4

    E_NOTICE

    8

    E_USER_ERROR

    256

    E_USER_WARNING

    512

    E_USER_NOTICE

    1024

    E_ALL

    2047

  • int error_log ( string message [, int message_type [, string destination ]]) : Sends the error message to the specified location. The specified location can be the default system log file, an email address, a remote destination, or a local log file. The first parameter represents the error message that is stored in the specified destination. The second parameter represents the message type. The third parameter represents one of the four destinations where the error message needs to be stored. The second parameter can take one of the following values:

    • : Stores the error messages in the default system log file.

    • 1 : Sends the error message to the destination email ID specified in the third parameter.

    • 2 : Saves the error message in a file present on a different computer in a network. The third parameter specifies the IP address and the port number of the destination computer.

    • 3 : Sends the error message to the destination file specified in the third parameter.


  • void trigger_error ( string error_msg [, int error_type]) : Triggers user-defined warnings, notices, or errors. The first parameter represents the error message and the second parameter represents the error type that needs to be triggered.

Listing 1-7 shows how to trigger errors using the trigger_error() function.

Listing 1-7: Generating Errors Using the trigger_error() Function
start example
 <?php // set the error reporting level for this script error_reporting(E_USER_ERROR); if (assert($divisor == 0))  {   error_log("Cannot perform division by zero", 3, "var/www/html/PHP_XML/error.log");   trigger_error("Cannot perform division by zero", E_USER_ERROR); } ?> 
end example
 

The above listing generates an error that stops the execution of the script if the condition passed to the assert() function is true. In the above listing:

  • The assert() function checks whether the divisor is zero or not.

  • The error_log() function sends the message, Cannot perform division by zero, to the log file specified by the second parameter when the divisor is zero.

Save the above listing as Trigger.php in the PHP_XML folder.

Figure 1-7 shows the output when Trigger.php is viewed in the Web browser:

click to expand: this figure shows the error triggered by the trigger_error() function. the message, cannot perform division by zero, is displayed on the web page.
Figure 1-7: Viewing Trigger.php

You can also define your own custom error handlers. You need to define a function that acts as an error handler. The syntax to declare a custom error handling function is:

 function func_name($errorno, $errorstr [,$errorfile, $errorline, $errorcontext]) 

The above syntax shows how to declare an error handling function. In the above code:

  • The func_name represents the name of the error-handling function.

  • The function must accept at least two parameters and a maximum of five parameters.

  • The first two parameters represent error number and error description. The remaining parameters are optional.

  • The third parameter represents the file name in which the error occurred.

  • The fourth parameter represents the line number, and the fifth parameter represents the context in which the error occurred.

After defining an error handling function, you need to set it as the error handler using the set_error_handler() function. This function takes the name of the error handling function as a parameter.

Listing 1-8 shows how to use a custom error handler:

Listing 1-8: Using Custom Error Handler
start example
 <php error_reporting(E_ALL); function ErrHandler($errorno, $errorstr, $errorfile, $errorline)  {    $display = true;    $notify = false;    $halt_script = false;    $error_msg = "<br>The $errorno error is occurring at $errorline in    $errorfile<br>";    switch($errorno)     {       case E_USER_NOTICE:       case E_NOTICE:       $halt_script = false;       $notify = true;       $label = "<B>Notice</B>";       break;       case E_USER_WARNING:       case E_WARNING:       $halt_script = false;       $notify = true;       $label = "<b>Warning</b>";       break;       case E_USER_ERROR:       case E_ERROR:       $label = "<b>Fatal Error</b>";       $notify=true;       $halt_script = false;       break;       case E_PARSE:       $label = "<b>Parse Error</b>";       $notify=true;       $halt_script = true;       break;       default:       $label = "<b>Unknown Error</b>";       break;    }    if($notify)     {       $msg = $label . $error_msg;       echo $msg;    }    if($halt_script) exit -1; } $error_handler = set_error_handler("ErrHandler"); echo "<BR><H2>Using Custom Error Handler</h2><BR>"; trigger_error("<BR>Error caused by E_USER_NOTICE</BR>", E_USER_NOTICE); trigger_error("<BR>Error caused by E_USER_WARNING</BR>", E_USER_WARNING); trigger_error("<BR>Error caused by E_USER_ERROR</BR>", E_USER_ERROR); trigger_error("<BR>Error caused by E_PARSE</BR>", E_PARSE); ?> 
end example
 

The above listing defines a custom error handler function, ErrHandler(), which handles the error generated by the trigger_error() function. In the above listing:

  • The $display variable is a configuration flag that indicates whether to display the error on the Web page or not. The configuration flags are used for the proper functioning of PHP scripts.

  • The $notify variable is another configuration flag that specifies whether the error should be notified to the end user or not. The default value for the $notify variable is false.

  • The $halt_script configuration variable specifies whether to stop the execution of the PHP script when a fatal error occurs. The default value of the $halt_script variable is true.

  • The $error_msg variable represents the error message to be displayed when an error occurs.

  • The switch statement execute statements for any error type based on the value of the $error variable.

  • The $notify variable displays the error message.

  • The ErrHandler() function is set as the error handler using the set_error_handler() function.

  • The trigger_error() function triggers the error of each of the error types.

Note  

The trigger_error() function can only trigger error of the E_USER types. It cannot trigger error for standard error types. Save the above listing as Trigger2.php.

Figure 1-8 shows the output when Trigger2.php is viewed in the Konqueror Web browser:

click to expand: this figure shows that the custom error handler is called four times by the trigger_error() function. the fourth error is not of the e_parse type because the trigger_error() function only accepts errors of the e_user types.
Figure 1-8: Viewing Trigger2.php

Classes and Objects

A class defines the properties and methods of an object. The properties are represented by the variables defined in the class and a method represents a function associated with an object. If student is a class, the variables in the student class represent the attributes of the student object, such as name and age of a student, and a method can be defined to calculate the grade. You can create classes in PHP using the keyword, class. The syntax to define a class is:

Defining a Class

 <?php class Class_name {    var $variables;    function class_function($arg1, $arg2)    {       // Statements to run within the class function       $this variables=$arg1;    } } ?> 

The above syntax shows the use of the keyword, class, for creating a class. In the above syntax:

  • The Class_name parameter indicates the name of the class that you are creating.

  • The $variables parameter indicates the class variable in the class.

  • The class_function parameter indicates the name of the class function.

  • The keyword, this , access the current object properties and methods. Using the this variable, you can access properties to assign values, such as $arg1, to it.

You create objects of a class to use the methods defined in the class. An object is an instance of the class that you use to call the class functions and assign values to the class variables. The syntax to create objects of a class is:

 $object= new Class_name; $object->class_function(); 

The above syntax shows the use of the keyword, new, to create an object, $object. The Class_name parameter indicates the name of the class for which you are creating the object. The keyword, this, is used to call the class_function() method of the current class object.

Listing 1-9 shows the process of creating classes and objects in PHP:

Listing 1-9: Using PHP Classes and Objects
start example
 <?php class emp {    var $name;    var $address;    var $dept;    function assign_info($n,$a,$d)    {       $this->name=$n;       $this->state=$a;       $this->dept=$d;    }    function display_info()    {       echo("<p>Employee Name : $this->name");       echo("<p>State : $this->state");       echo("<p>Department : $this->dept");    } } $empobj = new emp; $empobj->assign_info("Angela Jone","California","Accounts"); echo("<center><h2>Displaying Employee Information</h2></center>"); echo("<font size=4>"); $empobj->display_info(); echo("</font>"); ?> 
end example
 

The above listing defines a class, emp, with the class variables, $name, $state, and $dept. In the above listing:

  • The emp class also defines the method, assign_info() and display_info().

  • The assign_info() method assigns values to the class variables.

  • The display_info() method displays the values assigned to the class variables.

Save the above listing as Classes.php in the PHP_XML folder.

Figure 1-9 shows the output when Classes.php is viewed in the Web browser:

click to expand: this figure shows the employee name, state, and address information displayed using the display_info() method of the emp class.
Figure 1-9: Viewing Classes.php

A constructor is a special function in a class that is executed at the time of object creation. You can create a constructor in PHP by defining a function with the same name as the class name.

Listing 1-10 shows how to define a constructor for a class:

Listing 1-10: Creating Constructors with Classes
start example
 <?php class student {    var $name;    var $age;    var $grade;    function student($n,$a,$g)    {       $this->name=$n;       $this->age=$a;       $this->grade=$g;    }    function display_info()    {       echo("<p>Name : $this->name");       echo("<p>Age : $this->age");       echo("<p>Grade : $this->grade");    } } $sobj = new student("Rick Carter","15","A"); echo("<center><h2>Displaying Student Information</h2></center>"); echo("<font size=4>"); $sobj->display_info(); echo("</font>"); ?> 
end example
 

The above listing defines the constructor for the class, student. In the above listing:

  • The constructor, student, is a parameterized constructor because it accepts three arguments, $n, $a, and $g, and assigns them to the variables of the object created of this class.

  • The values are passed to the constructor and assigned to the class variables at the time of object initialization.

Save the above listing as Constructor.php in the PHP_XML folder.

Figure 1-10 shows the output when Constructor.php is viewed in the Web browser:

click to expand: this figure shows that the information passed to the constructor of the student class is displayed on the web page.
Figure 1-10: Viewing Constructor.php

Working with Files

You can perform the read, write, and append operations on PHP files. You need to open a file before you perform the read and write operations on it. You can open existing files using the PHP function, fopen(). The syntax to use the fopen() function is:

 $fobj=fopen("FileURL","Mode"); 

In the above syntax:

  • The parameter, FileURL, indicates the name of the file that is opened using the fopen() function.

  • The parameter, Mode, defines the mode in which you open a file, such as the read, write, and append modes.

Table 1-6 lists the various modes in which you can open a file:

Table 1-6: File Open Modes

Symbol

Mode

Are

Represents read-only mode.

r+

Represents read and write mode.

W

Represents write mode.

w+

Represents read and write mode. Creates a new file if the file does not exist.

A

Represents append mode.

a+

Represents append mode. Creates a new file if the file does not exist.

You can read a file after you have opened it. PHP provides the fread() function to read the content of a file. The syntax of the fread() function is:

 $text=fread(FileObject, filesize(FileURL)); 

In the above syntax, the parameter, FileObject, represents the name of the file to be read. The filesize() function calculates the size of the file passed to it as parameter, FileURL.

You can write data to a file after you open it in the write or append modes. PHP provides the fputs() function to write data to the file. The syntax to use the fputs() function is:

 fputs(FileObject, $text); 

In the above syntax:

  • The FileObject parameter represents the file in which data needs to be written.

  • The $text parameter indicates the text that is written to the file.

Listing 1-11 shows how to use the file handling functions to display the content of a text file:

Listing 1-11: File Handling Functions
start example
 <?php $file='info.txt'; $fobj=fopen($file,"r"); $text=fread($fobj, filesize($file)); echo("<h2><font color='blue'>Displaying Content of a Text File</font><h2>"); echo("<br>"); echo("<font size=3>"); echo($text); echo("</font>"); fclose($fobj); ?> 
end example
 

The above listing shows how to display the content of a text file. In the above listing:

  • The fopen() function opens the info.txt file in the read-only mode.

  • The fread() function reads the content of the info.txt file.

  • The fclose() function closes the file object after the information of the text file is displayed on the Web page.

Save the above listing as File.php in the PHP_XML folder.

Create the info.txt file in the PHP_XML folder. The following code shows the content of info.txt file:

Hello World. This is a test file.

Figure 1-11 shows the output when File.php is viewed in the Web browser:

click to expand: this figure shows the content of the info.txt file displayed on the web page.
Figure 1-11: Viewing File.php



Integrating PHP and XML 2004
Integrating PHP and XML 2004
ISBN: N/A
EAN: N/A
Year: 2004
Pages: 51

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