jump to content

Next Previous Contents

2. Tutorial

The on-line manual at the PHP siteexternal link is extremely good. There are some additional links provided there, to different tutorials. This section, however is to just quickly get you familiar with PHP. It is in no way exhaustive. Just helps you get started writing PHP scripts.

2.1 Pre-requisites

You must have a working webserver with PHP support. Let us assume that all of your files with PHP code have an extension .php3.

2.2 PHP setup

Create a file called test.php3 with the contents as below:

<? phpinfo(); ?>
Then point your browser to this file. Study the page and you'll know what options your PHP installations have.

2.3 Syntax

Like mentioned before, you can put PHP and HTML code in your file. So, you must have a way to distinguish between PHP and HTML code. We can do this in multiple ways. Pick one that you like and stick to that!

Escaping from HTML

Here are the possible ways to escape your PHP code from HTML.

Statements

In PHP, this is same as in Perl or C. You use the semi-colon (;). The closing tag for your escape from HTML also implies an end-of-statement.

Comments

PHP supports C, C++ and Unix style comments.

Hello World!

With this basic info, let us create a PHP program which will just print the standard message!



<HTML>
    <HEAD>
        <TITLE>
        <?
            echo "Hello World!";
        ?>
        </TITLE>
    </HEAD>
    <BODY>
        <H1>
            First PHP page
        </H1>
        <HR>
        <?
        // Single line C++ style comment
        /*
         printing the message
        */
        echo "Hello World!";
        # Unix style single line comment
        ?>
    </BODY>
</HTML>


2.4 Data Types

PHP supports integers, floats, strings, arrays and objects. The type of the variable is usually not set by the programmer, but determined by PHP at run-time (good riddance!). However, types can be expressly changed if necessary, using cast or settype() functions.

Numbers

Numbers can be integers or floating point numbers. You can specify a number using any of the following syntaxes.

$a = 1234; # decimal number
$a = -123; # a negative number
$a = 0123; # octal number (equivalent to 83 decimal)
$a = 0x12; # hexadecimal number (equivalent to 18 decimal)
$a = 1.234; # floating point number. "double"
$a = 1.2e3; # exponential format for double

Strings

Strings can be defined by using single quotes or double quotes. Whatever is inside single quotes is taken literally and values inside double quotes will be expanded. Backslash (\) can be used to escape special characters.

$first = 'Hello';
$second = "World";
$full1 = "$first $second"; # yields Hello World
$full2 = '$first $second';# yields $first $second
You can mix strings and numbers using arithmetic operators. Strings are then converted to numbers, using the initial portion. PHP manual has examples.

Arrays & Hashes

Arrays and hashes are implemented in the same way. How you use it determines what you get. You create arrays using list() or array() functions, or by explicitly setting values. Array index starts from 0. Though not explained here, you can have multi- dimensional arrays too.

$a[0] = "first";  // a two element array
$a[1] = "second"; 
$a[] = "third"; // easy way to append to the array.
               // Now, $a[2] has "third"
echo count($a); // prints 3, number of elements in the array
// create a hash in one shot
$myphonebook = array (
        "sbabu" => "5348",
        "keith" => "4829",
        "carole" => "4533"
  );
// oops, forgot dean! add dean
$myphonebook["dean"] = "5397";
// yeoh! carole's number is not that. correct it!
$myphonebook["carole" => "4522"
// didn't we tell that hashes and arrays are 
//implemented alike? let's see
echo "$myphonebook[0]"; // sbabu
echo "$myphonebook[1]"; // 5348
Some functions useful in this context are sort(), next(), prev(), each().

Objects

To create an object, use the new statement.

class foo {
        function do_foo () { 
                echo "Doing foo."; 
        }
}
$bar = new foo;
$bar->do_foo();

Changing Types

From the PHP manual - "PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which that variable is used. That is to say, if you assign a string value to variable var, var becomes a string. If you then assign an integer value to var, it becomes an integer."

$foo = "0";  // $foo is string (ASCII 48)
$foo++;      // $foo is the string "1" (ASCII 49)
$foo += 1;   // $foo is now an integer (2)
$foo = $foo + 1.3;  // $foo is now a double (3.3)
$foo = 5 + "10 Little Piggies"; // $foo is integer (15)
$foo = 5 + "10 Small Pigs";     // $foo is integer (15)
Type casting works just like in C. You can also use settype() function.

2.5 Variables & Constants

As you might've noticed, variables in PHP are prefixed with the dollar sign ($). All variables have local scope. To make a variable defined outside any function to be seen inside a function, you've to specify it using global. For values to be retained inside functions, you can use static variables too.

$g_var = 1 ; // global scope
function test() {
        global $g_var; // that's how you specify global variable
}
Slightly more advanced are variable variables. See the manual. These can be extremely useful at times.

PHP defines some constants internally. You can define your own constants using the define function, like define("CONSTANT","value").

2.6 Operators

PHP has all the common operators found in C, C++ or Java. Precedence rules are also same. Assignment operator is =.

Arithmetic & String

There is only one string operator.

Logical & Comparison

Logical operators are :

Comparison operators are : Like in C, PHP has the ternary operator (?:) too. Bit operators are also available.

Precedence

Just like in C or Java!

2.7 Control Structures

PHP has standard control structures you find in C. We will briefly cover these.

if, else, elseif, if(): endif

if ( expr1 ) {
 ...
} elseif (expr2) {
} else {
}

// or like in Python
if (expr1) :
   ...
   ...
elseif (expr2) :
   ...
else :
   ...
endif;

Loops. while, do..while, for

while (expr) { ... }
do {...} while (expr);
for (expr1; expr2; expr3) {...}
// or like in Python
while (expr) :
        ...
endwhile;

switch

Switch is an elegant replacement for multiple if-elseif-else structure.

switch ($i) {
        case 0:
                print "i equals 0";
        case 1:
                print "i equals 1";
        case 2:
                print "i equals 2";
}

break, continue

break breaks out of current looping control-scructures.

continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the beginning of the next iteration.

require, include

require is just like C's #include pre-processor directive. The file you specify with require is substituted in place. This means that you can't put require within if statements. To conditionally include code, we use include() function. It is a good practice to split PHP code into multiple files and inlcude only the necessary ones.

2.8 Functions

You can define your own functions as shown below. Return values can be any of the data types.

function foo ($arg_1, $arg_2, ..., $arg_n) {
        echo "Example function.\n";
        return $retval;
}
Any valid PHP code may appear inside a function, even other functions and class definitions. Functions must be defined before they are referenced.

2.9 Classes

Use the class construct to create classes. See the manual for a good explanation of classes.

class Employee {
    var $empno; // employee number
    var $empnm; // name

    function add_employee($in_num, $in_name){
        $this->empno = $in_num;
        $this->empnm = $in_name;
    }

    function show() {
        echo "$this->empno, $this->empnm";
        return;
    }

    function changenm($in_name){
        $this->empnm = $in_name;
    }
}

$sbabu = new Employee;
$sbabu->add_employee(10,"sbabu");
$sbabu->changenm("babu");

$sbabu->show();


Next Previous Contents