Introduction To PHP: Common Uses of PHP
Introduction To PHP: Common Uses of PHP
IV I.T
Introduction to PHP
PHP, or PHP: Hypertext Preprocessor, is a cross-platform server side scripting
language that is primarily used to create dynamic and interactive web pages, which means that
it can be used on almost every major operating system. It can be embedded into HTML and is
generally run on web servers that are running the Apache HTTP server software. It is free
software and is free to download and use.
PHP is a recursive acronym for "PHP: Hypertext Preprocessor".
PHP is an open source, server side scripting language that is embedded in HTML.
It is used to manage dynamic content, databases, session tracking, even build entire ecommerce sites.
PHP is compatible with all the major web servers like Apache, Microsoft IIS.
It is integrated with a number of popular databases, including MySQL, PostgreSQL,
Oracle, Sybase, Informix, and Microsoft SQL Server.
PHP supports a large number of major protocols such as POP3, IMAP, and LDAP.
PHP4 added support for Java and distributed object architectures (COM and CORBA),
making n-tier development a possibility for the first time.
PHP Syntax is very similar to C and Perl languages.
Common uses of PHP
PHP performs system functions, i.e. from files on a system it can create, open, read,
write, and close them.
PHP can handle forms, i.e. gather data from forms, save data into database.
We can add, delete, and modify elements within our database through PHP.
Through PHP, we can access cookies variables and can set cookies.
Using PHP, we can restrict users to access some pages of our website.
It can encrypt data.
Characteristics of PHP
Five important characteristics make PHP's practical nature possible:
Simplicity
Efficiency
Security
Flexibility
Familiarity
Familiarity
Programmers from many backgrounds will already be familiarized with the PHP
language. Many of the languages constructs are borrowed from C and Perl, and in many cases
PHP code is almost indistinguishable from the typical C program.
Simplicity
There is no need to include libraries, special compilation directives, or anything. The
PHP engine simply begins executing the code after the first escape sequence (<?php). If the
code is syntactically correct, it will be executed exactly as it is displayed.
IV I.T
Efficiency
Efficiency is an extremely important consideration for working in a multiuser
environment such as the WWW. PHP 4.0 introduced resource allocation mechanisms and more
support for object-oriented programming, in addition to session management features.
Security
PHP provides developers and administrators with a flexible and efficient set of security
safeguards. These safeguards can be divided into two frames of reference: system level and
application level.
Flexibility
Because PHP is an embedded language, it is extremely flexible towards meeting the
needs of the developer. Although PHP is generally used in conjunction with HTML, it can also
be integrated with the languages like JavaScript, WML, XML, and many others. Browser
dependency is not an issue because PHP scripts are compiled entirely on the server side before
being sent to the user.
Server side Processing with PHP
Generally, PHP works in partnership with a web server, which enables us to build
interactive and dynamic web pages. A web server is the software that delivers web pages to
our website's users. The PHP software works in conjunction with the web server to allow the
functionality necessary to deliver the interactive and dynamic web pages.
When a website user goes to a web page with a .php extension, for example by typing
the URL into the web browser directly or by clicking a link, the request is sent to a web server.
That request is then sent to the PHP interpreter.
The PHP interpreter also communicates with file systems, databases and email servers
as needed, and then delivers the request to the web server to return to the web browser.
In comparison, when a website user goes to a purely HTML generated web page; the
server sends HTML data to the web browser without having the code interpreted.
1. The user enters a web page address in the browsers location bar.
2. The browser breaks apart that address and sends the name of the page to the
host. For example, http://www.phone.com/login.php requests the page
login.php from www.phone.com.
3. The web server process on the host receives the request for login.php.
4. The web server reads the login.php file from the hosts hard drive.
5. The web server detects that the PHP file isnt just a plain HTML file, so it asks
another processthe PHP interpreterto process the file.
IV I.T
6. The PHP interpreter executes the PHP code that it finds in the text it received
from the web server process. Included in that code are calls to the MySQL
database.
7. PHP asks the MySQL database process to execute the database calls.
8. The MySQL database process returns the results of the database query.
9. The PHP interpreter completes execution of the PHP code with the data from
the database and returns the results to the web server process.
10. The web server returns the results in the form of HTML text to the browser.
11. The web browser uses the returned HTML text to build the web page on users
screen.
PHP Environment
In order to develop and run PHP Web pages, three vital components need to be installed on
our computer system.
Web Server - PHP will work with virtually all Web Server software, including
Microsoft's Internet Information Server (IIS) but then most often used is freely
available Apache Server.
Database - PHP will work with virtually all database software, including Oracle and
Sybase but most commonly used is freely available MySQL database.
PHP Parser - In order to process PHP script instructions a parser must be installed to
generate HTML output that can be sent to the Web Browser.
PHP Syntax
The syntax for PHP scripting blocks start with a <?php delimiter and end with a ?>
delimiter. A PHP scripting block can be placed anywhere within an HTML document. If PHP
is included within an HTML document, the document must have a .php extension.
<?php
// PHP scripting block
?>
There are other PHP delimiters that can be used, however, it is recommended that you
use the standard form <?php and ?> delimiters for maximum compatibility.
Other PHP delimiters that we can use are
Shorthand delimiters (<? ?>).
ASP style delimiters (<% %>)
Placing our code inside <script> tags with the language attribute set to php.
The examples below show us how each style of PHP delimiter looks.
On servers that have shorthand support enabled, we can use the scripting block
delimiters <? and ?>.
Syntax:
IV I.T
<?
// PHP code
?>
We can use the ASP style delimiters <% and %> by turning on the asp_tags directive.
Syntax:
<%
// PHP code
%>
We can also place PHP code within the <script> and </script> tags with the language
attribute set to php
Syntax
<script language="php">
// PHP code
</script>
Each PHP statement must end with a semi-colon (;). This tells the PHP interpreter that
that PHP statement has ended. If a semi-colon is not included at the end of the line of code, the
interpreter will assume that the PHP statement continues onto the next line.
The PHP interpreter condenses all sequential whitespace in PHP scripts to a single
whitespace. This allows programmers to structure their code into a more readable format.
PHP comment tags
PHP allows us to add comments that are visible to us, the programmer, to PHP code
without the PHP interpreter trying to execute the comments as code. The PHP comments tags
are // for single-line comments and enclosing /* and */ tags for multiple-line comments.
<?php
// this is a single-line comment
?>
<?php
/*
this is a multiple-line comment
this is a multiple-line comment
*/
?>
IV I.T
Step 3:
Open any web browser(Chrome, IE, Firefox, Safari, Opera etc.) . Simply type
http://localhost/myFirstPHPScript.php in the address bar. Then we get the page like
PHP Variables
Variables are used for storing values, such as numbers, strings or function results, so
that they can be used many times in a script. Once a variable is declared, it can be used over
and over again throughout your script.
IV I.T
IV I.T
Integers
They are whole numbers, without a decimal point, like 4195 represented in both
positive and negative. Integers can be assigned to variables, or they can be used in expressions,
like so:
$int_var = 12345;
$another_int = -12345 + 12345;
Integer can be in decimal (base 10), octal (base 8), and hexadecimal (base 16) format.
Decimal format is the default, octal integers are specified with a leading 0, and hexadecimals
have a leading 0X.
For most common platforms, the largest integer is 2,147,483,647, and the smallest
integer is -2,147,483,647.
Doubles
They like 3.14159 or 49.1. By default, doubles print with the minimum number of
decimal places needed. For example, the code:
$many = 2.2888800;
$many_2 = 2.2111200;
$few = $many + $many_2;
print(.$many + $many_2 = $few<br>.);
It produces the following browser output:
2.28888 + 2.21112 = 4.5
Boolean
They have only two possible values either TRUE or FALSE.
if (TRUE)
print("This will always print<br>");
else
print("This will never print<br>");
Strings
They are sequences of characters, like "PHP supports string operations". Following are
valid examples of string.
$string_1 = "This is a string in double quotes";
$string_2 = "This is a somewhat longer, singly quoted string";
$string_39 = "This string has thirty-nine characters";
$string_0 = ""; // a string with zero characters
Singly quoted strings are treated almost literally, whereas doubly quoted strings
replace variables with their values as well as specially interpreting certain character sequences.
<?
$variable = "name";
$literally = 'My $variable will not print!\\n';
print($literally);
$literally = "My $variable will print!\\n";
print($literally); ?>
7
IV I.T
IV I.T
Local Variables
Variables that are defined in the body of a function are local for the function. Local
variables are not accessible in the global scope.
Global Variables
Variables that are defined in the main body of a script are global variables. Global variables
are not accessible in the local scope.
To show the difference between local and global variables, the below PHP code
demonstrated
<?php
$globalVar = 1;
function localFunc() {
echo "The value in localFunc is: $globalVar.<br />";
}
function globalFunc() {
global $globalVar;
echo "The value in globalFunc is: $globalVar";
}
localFunc();
globalFunc();
?>
The PHP code above outputs:
The value in localFunc is:The value in globalFunc is: 1
IV I.T
PHP Constants
A PHP constant is a variable that cannot be changed after the initial value is assigned
during the execution of the script. We can create a constant variable using the define ()
function. The function accepts 2 arguments.
Syntax:
define (<constant name>, <value>);
The first must be a string and represents the name which will be used to access the
constant. A constant name is case-sensitive by default and by convention, is always
uppercase. A valid constant name starts with a letter or underscore, followed by any
combination of letters, numbers or underscores. Constant names must be in quotes
when they are defined.
The second argument is the value of the constant and can be a string or numbers and
can be set explicitly.
The scope of a constant is global, which means that we can access constants anywhere in
our script without regard to scope.
<?php
define ("WEBSITE", "WebDevelopmentTutorials.com");
define(PI,3.17);
echo WEBSITE;
EchoPI value is:.PI;?>
PHP Operators
In PHP, operators are used to manipulate or perform operations on values and expressions.
Operators allow us to assign values to variables, perform arithmetic operations, concatenate
strings, compare values and perform Boolean operations.
PHP Assignment Operators
PHP Arithmetic Operators
PHP String Concatenation Operator
PHP Increment and Decrement Operators
PHP Logical Operators
PHP Comparison Operators
PHP Arithmetic Operators
PHP arithmetic operators are used to perform various arithmetic operations. They are
Operator Description
Example
A + B will give
30
A - B will give 10
A * B will give
200
B / A will give 2
10
++
--
IV I.T
B % A will give
0
A++ will give 11
A-- will give 9
Operator Description
=
Example
+=
-=
*=
operand
the left operand
and C *= A is equivalent to C = C * A
MultiplyfromAND
assignment
assign
the result
to left operand
operator,
It multiplies
right
/=
operand
with assignment
the left operand
and C /= A is equivalent to C = C / A
Divide AND
operator,
assign
the
result
to
left
operand
It divides left operand with the
right
operandAND
and assign
the result C %= A is equivalent to C = C %
Modulus
assignment
to
left
operand
operator, It takes modulus using A
two operands and assign the result
left operand Operator
PHP StringtoConcatenation
The PHP concatenation operator (.) is used to combine 2 sting values to create one
string. The concatenation operator us useful when WE are combining strings with values from
constants and arrays.
<?php
$variable1="Hello";
$variable2="World";
echo $variable1 . " " . $variable2;
?>
The code above outputs:
Hello World
%=
11
IV I.T
12
IV I.T
$value--(post-drecrement) operator
The PHP $value--(post-drecrement) operator subtracts 1 from a value after the value is
used in the expression in which it is contained.
<?php
$value = 2;
echo $value--;
echo "<br />;
echo $value;
?>
The code above outputs:
2
1
PHP Logical Operators
PHP logical operators are used to perform Boolean operations to compare one value to another
to determine if a statement is true or false.
Operator Description
and
Example
or
&&
||
Operator Description
Example
==
Checks if the values of two operands are equal or not, if yes (A == B) is not
then condition becomes true.
true.
!=
>
IV I.T
Checks if the value of left operand is greater than the value of (A > B) is not
right operand, if yes then condition becomes true.
true.
Checks if the value of left operand is less than the value of (A < B) is true.
right operand, if yes then condition becomes true.
<
>=
Checks if the value of left operand is greater than or equal to (A >= B) is not
the value of right operand, if yes then condition becomes true.
true.
Checks if the value of left operand is less than or equal to the (A <= B) is true.
value of right operand, if yes then condition becomes true.
<=
Conditional Statements
Conditional statements allow us to specify blocks of code which will be executed only if
certain conditions are met. PHP supports following four decision making statements:
If statement: It allows one to execute select lines of code only when specified
conditions are true.
if...else statement - use this statement if you want to execute a set of code when a
condition is true and another if the condition is not true
elseif statement - is used with the if...else statement to execute a set of code if one of
several condition are true
switch statement If we wish to test a single expression against a number of values,
the switch statement is used.
if Statement
The if statement is one of the most important features of every programming language.
It allows one to execute lines of code only when specified conditions are true.
Syntax
if (condition)
code to be executed if condition is true;
For Example
<?php
$number = 5;
if ($number < 10)
echo "5 is less than 10.";
?>
The code above outputs:
5 is less than 10.
If there will be more than one statement following the if condition, we will need to
enclose the statements in brackets ({}). For single statements, the use of the brackets is
optional.
<?php
$number = 5;
14
IV I.T
<?php
$number = 5;
if ($number < 10)
{
echo "5 is less than 10";
}
else
{
echo "5 is less than 10 is not true";
}
?>
The code above outputs:
5 is less than 10
elseif statement
PHP provides the elseif keyword to test alternative conditions if the condition in the if
portion of the statement is not true. Any number of elseif statements may be used with an if
statement. The final else branch then allows us to specify code that should be executed if none
of the if or elseif conditions is true.
15
IV I.T
Syntax
if (condition)
code to be executed if condition is true;
elseif (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;
For example
<?php
$number = 10;
if ($number < 10)
{
echo "the variable \$number is less than 10";
}
elseif ($number == 10)
{
echo "the variable \$number is equal to 10";
}
else
{
echo "the variable \$number is less than 10 is not true";
}
?>
The code above outputs: the variable $number is equal to 10
Switch Statement
A PHP switch statement allows us to set up a list of conditions with a block of
statements for each condition. The switch statement tests the value of one variable and
executes the block of statements for the matching variable, or cases.
Syntax
switch (expression)
{
case label1:
code to be executed if expression = label1;
break;
case label2:
code to be executed if expression = label2;
break;
default:
code to be executed
if expression is different
from both label1 and label2;
}
16
IV I.T
For Example
<?php
$state = "TX";
switch($state){
case "CA";
echo "I live in California";
break;
case "NY";
echo "I live in New York";
break;
case "TX";
echo "I live in Texas.";
break;
}
?>
Iterative Statements
Loops are a means of executing a block code a given number of times, or until a certain
condition is met.
There are a number of different loop statements in PHP:
While loop : PHP while loops will execute a block of code if and as long as a specified
condition is true.
do...while loop : PHP do while loops execute a block of code at least once and then it will
repeat the loop as long as a condition is true.
for loop : PHP for loops execute a block of code a specified number of times.
foreach loop : PHP foreach are used to loop through arrays.
The while loop
The while statement will execute a block of code if and as long as a test expression is true.
If the test expression is true then the code block will be executed. After the code has executed
the test expression will again be evaluated and the loop will continue until the test expression
is found to be false.
Syntax
while (condition)
{
code to be executed;
}
17
IV I.T
Example
This example decrements a variable value on each iteration of the loop and the counter
increments until it reaches 10 when the evaluation is false and the loop ends.
<html>
<body>
<?php
$i = 0;
$num = 50;
while( $i < 10)
{
$num--;
$i++;
}
echo ("Loop stopped at i = $i and num = $num" );
?>
</body>
</html>
This will produce following result:
Loop stopped at i = 1 and num = 40
do...while Loop
do ... while statements are similar to while statements, except that the condition is
tested at the end of each iteration, rather than at the beginning. This means that the loop will
always execute at least once
Syntax
do
{
code to be executed;
}while (condition);
Example
The following example will increment the value of i at least once, and it will continue
incrementing the variable i as long as it has a value of less than 10:
<html>
<body>
<?php
$i = 0;
$num = 0;
do
{
$i++;
}while( $i < 10 );
18
IV I.T
For statement
The for statement is used when we know how many times you want to execute a
statement or a block of statements.
Syntax
for (initialization; condition; increment)
{
code to be executed;
}
The for statement takes three expressions inside its parentheses, separated by semicolons. The first is an assignment statement to initialize the loop control variable. This
statement is executed only once, before the first iteration of the loop. The second is a Boolean
expression that is evaluated at the beginning of each iteration. If this expression evaluates to
true, the iteration proceeds. If false, the loop terminates. The third is a statement which
executes at the end of each iteration of the loop. It is usually used to increment or decrement
the loop control variable.
Example
<html>
<body>
<?php
$a = 0;
$b = 0;
for( $i=0; $i<5; $i++ )
{
$a += 10;
$b += 5;
}
echo ("At the end of the loop a=$a and b=$b" );
?>
</body>
</html>
19
IV I.T
PHP Arrays
An array is a data structure that stores one or more similar type of values in a single
value. For example if you want to store 100 numbers then instead of defining 100 variables it
is easy to define an array of 100 length.
There are three different kinds of arrays and each array value is accessed using an ID which is
called array index.
20
IV I.T
Numeric array - An array with a numeric index. Values are stored and accessed in
linear fashion
Associative array - An array with strings as index. This stores element values in
association with key values rather than in a strict linear index order.
Multidimensional array - An array containing one or more arrays and values are
accessed using multiple indices
Numeric Array
These arrays can store numbers, strings and any object but their index will be represented by
numbers. By default array index starts from zero.
Creating Numeric Array
We can create numeric array in two different ways.
Direct assignment
The simplest way to create an array is to assign a value into the specific index of the
array, like this
$my_array[1] = The first thing in my array that I just made;
If $my_array was an unbound variable before this statement, it will now be a variable bound
to an array with one element. If instead $my_array was already an array, the string will be
stored in association with the integer key 1.
If no value was associated with that number before, a new array slot will be created to hold it.
If a value was associated with 1, the previous value will be overwritten
The array() construct
The other way to create an array is via the array() construct, which creates a new array
from the specification of its elements. In its simplest version, array() is called with no
arguments, which creates a new empty array. In its next simplest version, array() takes a
comma separated list of elements to be stored. The result is that the elements are stored in the
array in the order specified and are assigned integer keys beginning with zero.
For example, the statement:
$fruit_basket = array(apple, orange, banana, pear);
causes the variable $fruit_basket to be assigned to an array with four string elements (apple,
banana, orange, pear), with the indices 0, 1, 2, and 3, respectively.
For example
<html>
<body>
<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
foreach( $numbers as $value )
{
echo "Value is $value <br />";
}
/* Second method to create array. */
21
IV I.T
$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";
foreach( $numbers as $value )
{
echo "Value is $value <br />";
}
?>
</body>
</html>
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Value is one
Value is two
Value is three
Value is four
Value is five
Associative Arrays
The associative arrays are very similar to numeric arrays in term of functionality but they are
different in terms of their index. Associative array will have their index as string so that you
can establish a strong association between key and values.
Specifying indices using array()
The array() constructs offers us a special syntax for specifying key/value pairs
separated by commas, where the key and value are separated by the special symbol =>.
Consider the following statement:
$fruit_basket = array(red => apple, orange => orange, yellow => banana, green =>
pear);
Example
<body>
<?php
/* First method to associate create array. */
$salaries = array(
"mohammad" => 2000,
"qadir" => 1000,
"zara" => 500
);
22
IV I.T
IV I.T
foreach structure
This is the simplest way of retrieving the array elements iteratively. The syntax for
foreach is
foreach ($array_variable as $value_variable) {
// .. do something with the value in $value_variable
}
If the array is having key/value pair elements, then the syntax for foreach statement is
foreach ($array_variable as $key_var => $value_var) {
// .. do something with $key_var and/or $value_var
}
Iterating with current() and next()
The current() function returns the stored value that the current pointer points to.
When an array is newly created with elements, the element pointed to will always be the first
element. The next() function first advances that pointer and then returns the current value
pointed to. If the next() function is called when the current pointer is already pointing to the
last stored value then the function returns a false value.
$fruit_basket = array(apple, orange, banana);
$current_item = current($fruit_basket);
if ($current_item)
print($current_item<BR>);
else
print(Theres nothing to print);
while($current_item = next($fruit_basket))
print($current_item<BR>);
24
IV I.T
Multidimensional Arrays
A multi-dimensional array each element in the main array can also be an array. And each
element in the sub-array can be an array, and so on. Values in the multi-dimensional array are
accessed using multiple index.
Example
In this example we create a two dimensional array to store marks of three students in three
subjects:
This example is an associative array, you can create numeric array in the same fashion.
<html>
<body>
<?php
$marks = array(
"mohammad" => array
(
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),
"qadir" => array
(
"physics" => 30,
"maths" => 32,
"chemistry" => 29
),
"zara" => array
(
"physics" => 31,
"maths" => 22,
"chemistry" => 39
)
);
/* Accessing multi-dimensional array values */
echo "Marks for mohammad in physics : " ;
echo $marks['mohammad']['physics'] . "<br />";
echo "Marks for qadir in maths : ";
echo $marks['qadir']['maths'] . "<br />";
echo "Marks for zara in chemistry : " ;
echo $marks['zara']['chemistry'] . "<br />";
?>
</body>
</html>
This will produce following result:
Marks for mohammad in physics : 35
Marks for qadir in maths : 32
Marks for zara in chemistry : 39
25
IV I.T
IV I.T
27
IV I.T
p*
p?
It matches any string containing zero or more p's. This is just an alternative
way to use p*.
p{N}
p{2,3}
p{2, }
p$
^p
PHP currently offers some functions for searching strings using POSIX-style regular
expressions:
28
IV I.T
Function
Description
ereg()
eregi()
split()
The split() function will divide a string into various elements, the
boundaries of each element based on the occurrence of pattern in string.
Example
<?php
if (ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})", $date, $regs)) {
echo "$regs[3].$regs[2].$regs[1]";
} else {
echo "Invalid date format: $date";
}
?>
PHP Functions
PHP function is a piece of code which takes one or more input values in the form of
parameter and does some processing and returns a value.
There are two parts for the functions
Creating a PHP Function
Calling a PHP Function
Creating PHP Function
It is very easy to create our own PHP function. While creating a function, its name
should start with keyword function and all the PHP code should be put inside {and } braces as
shown in the following example below:
<html>
<head>
<title>Writing PHP Function</title>
</head>
<body>
29
IV I.T
<?php
/* Defining a PHP Function */
function writeMessage()
{
echo "You are really a nice person, Have a nice time!";
}
/* Calling a PHP Function */
writeMessage();
?>
</body>
</html>
This will display following result:
You are really a nice person, Have a nice time!
PHP Functions with Parameters
PHP allows us to pass the parameters inside a function. We can pass as many as
parameters our like. These parameters work like variables inside the function. Following
example takes two integer parameters and adds them together and then prints them.
<html>
<head>
<title>Writing PHP Function with Parameters</title>
</head>
<body>
<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>
</body>
</html>
This will display following result:
Sum of the two numbers is : 30
PHP Functions with returning value
A function can return a value using the return statement in conjunction with a value or
object. The return stops the execution of the function and sends the value back to the calling
code.
30
IV I.T
For example
<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>
<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);
echo "Returned value from the function : $return_value
?>
</body>
</html>
This will display following result:
Returned value from the function : 30
Setting Default Values for Function Parameters
We can set a parameter to have a default value if the function's caller doesn't pass it.
Following function prints Hello in case of no value passed.
<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>
<?php
function printMe($param = Hello)
{
print $param;
}
printMe("This is test");
printMe();
?>
</body>
</html>
This will produce following result:
This is test
Hello
31
IV I.T
IV I.T
}
function getTitle(){
echo $this->title ." <br/>";
}
}
?>
Creating Objects in PHP
Once we defined the class, then we can create as many objects as we like of that class
type. Following is an example of how to create object using new operator.
$physics = new Books;
$maths = new Books;
$chemistry = new Books;
Calling Member Functions
After creating the objects, we will be able to call member functions related to that
object. One member function will be able to process member variable of related object only.
Following example shows how to set title and prices for the three books by calling
member functions.
$physics->setTitle( "Physics for High School" );
$chemistry->setTitle( "Advanced Chemistry" );
$maths->setTitle( "Algebra" );
$physics->setPrice( 10 );
$chemistry->setPrice( 15 );
$maths->setPrice( 7 );
Now we call another member functions to get the values set by in above example:
$physics->getTitle();
$chemistry->getTitle();
$maths->getTitle();
$physics->getPrice();
$chemistry->getPrice();
$maths->getPrice();
This will produce following result:
Physics for High School
Advanced Chemistry
Algebra
10
15
7
33
IV I.T
Constructor Functions
Constructor Functions are special type of functions which are called automatically
whenever an object is created. PHP provides a special function called __construct() to define
a constructor. We can pass as many as arguments we like into the constructor function.
For example
function __construct( $par1, $par2 ){
$this->price = $par1;
$this->title = $par2;
}
Now we don't need to call this function separately to set price and title. We can
initialize these two member variables at the time of object creation only. For example
$physics = new Books( "Physics for High School", 10 );
$maths = new Books ( "Advanced Chemistry", 15 );
$chemistry = new Books ("Algebra", 7 );
/* Get those set values */
$physics->getTitle();
$chemistry->getTitle();
$maths->getTitle();
$physics->getPrice();
$chemistry->getPrice();
$maths->getPrice();
This will produce following result:
Physics for High School
Advanced Chemistry
Algebra
10
15
7
Destructor
Like a constructor function we can define a destructor function using function
__destruct(). All the resources can be released with-in a destructor.
34
IV I.T
Opening a File
The fopen() function is used to open files in PHP. The first parameter of this function
contains the name of the file to be opened and the second parameter specifies in which mode
the file should be opened. If the fopen() function is unable to open the specified file, it returns
0 (false).
The file may be opened in one of the following modes:
Modes Description
r
r+
Write only. Opens and clears the contents of file; or creates a new file if it doesn't
exist
w+
Read/Write. Opens and clears the contents of file; or creates a new file if it doesn't
exist
Append. Opens and writes to the end of the file or creates a new file if it doesn't
exist
a+
Write only. Creates a new file. Returns FALSE and an error if file already exists
x+
Read/Write. Creates a new file. Returns FALSE and an error if file already exists
Example
<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
?>
Closing a File
The fclose() function is used to close an open file. For example
<?php
$file = fopen("test.txt","r");
//some code to be executed
fclose($file);
?>
35
IV I.T
36