Docstoc

PHP Basics

Document Sample
PHP Basics Powered By Docstoc
					PHP Basics
   Session # 1




          .
  Slides by npguy
            What is PHP?
• PHP is a high-level programming
  language used mostly for building web
  sites. The fullform of PHP is PHP
  Hypertext Preprocessor (in recursive
  term).
           So, Why PHP?
• PHP Is Free
• PHP Is Built for Web Programming
• PHP Is Cross-Platform .. Runs almost
  anywhere.
• PHP Is Widely Used .. Almost more than
  17 million sites and increasing……..
• PHP Hides Its Complexity
          Hey! PHP is Hot!
• Recent Independent survey shows PHP is
  in 4th position after Java as highly used
  language.
    PHP is like C, Java, Perl…
• Lots of syntactical features are similar to
  C,Java and Perl.
• PHP ….
     • Built in Garbage collection handles most of the
       memory handling task
     • Loosely type
     • Object Oriented features lots of resembles to Java
     • Great collection of resources … everything u need!
How Web Server works?
How PHP works?
    Client and server communication
              without PHP
.
    Client and server communication
                with PHP
.
            PHP in Action
• PHP can embedded into HTML. File
  extension should be .php, and is executed
  in the server. Lets see some examples…
                 Example 1
<html>
<head>
<title> example# 1 </title>
</head>
<body>
Hello! This example#1
<?php
 printf(“Hello PHP!”);
?>
</body>
</html>
                 Example 2
<html>
<head>
<title> example# 2 </title>
</head>
<body>
Hello! This example#2
<%
 print(“Hello PHP!”);
%>
</body>
</html>
                 Example 3
<html>
<head>
<title> example# 3 </title>
</head>
<body>
Hello! This example#3
<script language=php>
 echo “Hello PHP!”;
</script>
</body>
</html>
               Example 4
<html>
<head>
<title> example# 4 </title>
</head>
<body>
Hello! This example#3
<?=“Hello PHP!”; ?>
</body>
</html>
              Variables
In PHP, variables are denoted by $
followed by the variable's name.

$plates = 5;
$k = “Hello! PHP”
$total = $plates * 2;
     PHP is loosely typed!

PHP is loosely typed language. You don‟t
need to define the type of the variable or
constant, PHP engine will do for you.
Although you can use primitive data type
in PHP.
              Constant
A constant is an identifier (name) for a
simple value that cannot be changed. In
PHP, constant identifiers are always
uppercase.

define(“MAXITEM", 512);
define(“SECTORS", 40);
define(“TITLENAME", “College of IT");
 Printing Variable and Constant
<?
define(“TOTAL_STUDENT”,40);
$name = “College of IT”;
echo “I read in $name”;
print “I read in “.$name;
//printing constant value
echo “Total student “.TOTAL_STUDENT;
?>
Working with text and number
The simplest is to surround the string with
 single quotes:
 <?
print 'I would like a bowl of soup.';
print 'chicken';
print '06520';
print '"I am eating dinner," he growled.';
?>
               Text Strings
 You can include whitespace such as newlines in
  single-quoted strings:

print '<ul>
      <li>Beef Chow-Fun</li>
      <li>Sauteed Pea Shoots</li>
      <li>Soy Sauce Noodles</li>
    </ul>';
     Here document syntax
you can also define strings with the here
document syntax. A here document begins
with <<< and a delimiter word. It ends with
the same word at the beginning of a line.

For Example (next slide..)
          Here doc syntax
print <<<HTMLBLOCK
  <html>
  <head><title>Menu</title></head>
  <body bgcolor="#fffed9">
  <h1>Dinner</h1>
  <ul>
  <li> Beef Chow-Fun <li> Sauteed Pea
  Shoots <li> Soy Sauce Noodles </ul>
  </body> </html>
  HTMLBLOCK;
       String concatenation
To combine two strings, use a . (period),
the string concatenation operator.

print 'bread' . 'fruit';
print "It's a beautiful " . ' day.';
print "The price is: " . '$3.95';
print 'Inky' . 'Pinky' . 'Blinky' . 'Clyde';
        String concatenation
$city = “Kathmandu”;
$addr = “Sinamangal”;
$pc = “37/74”;
$to = “City”.$addr. ”Addr:”.$city. “Postal”.$pc;
print $to;
              Numbers
Numbers in PHP are expressed using
familiar notation, although you can't use
commas or any other characters to group
thousands.

print 56;
print 56.3;
print 0.774422;
                  Operators
•   Assignment Operator
•   Arithmetic Operator
•   Bitwise Operator
•   Error Handling Operator
•   Comparison Operator
•   Logical Operator
•   Execution Operators
•   Incrementing/Decrementing Operators
•   String Operators
•   Array Operator
•   Type Operator
        Assignment Operator
<?php

 $a = 3;
 $a += 5;
 $a = $a + 5;
 $b = "Hello ";
 $b .= "There!";
 just like $b = $b . "There!";

 ?>
         Arithmetic Operators
    Remember basic arithmetic from school?

•   -$a
•   $a + $b
•   $a - $b
•   $a * $b
•   $a / $b
•   $a % $b
              Bitwise operator
 Bitwise operators allow you to turn specific bits within an
 integer on or off. Remember C/C++?

<?php
  $a=4;
  $b=2;
  echo $a & $b;
  echo $a | $b;
  echo $a ^ $b;
  echo ~ $a;
  echo $a << $b;
  echo $a >> $b ;
?>
   Error Handling Operator
At sign (@) Operator, When prepended to
an expression, any errmsg that might be
generated by that expression will be
ignored.
<?php
   @$a = 1/0;
   $fp = @fopen(“test.txt”, “r”);
 ?>
      Comparison Operators
• a == $b
 TRUE if $a is equal to $b.

• $a === $b
  Identical TRUE if $a is equal to $b, and
  they are of the same type.
      Comparison Operators
• $a != $b
  Not equal TRUE if $a is not equal to $b.

• $a <> $b
  Not equal TRUE if $a is not equal to $b.

• $a !== $b
  Not identical TRUE if $a is not equal to $b,
  or they are not of the same type.
       Comparison Operators
• $a < $b
  Less than TRUE if $a is strictly less than $b.
• $a > $b
  Greater than TRUE if $a is strictly greater than $b.
• $a <= $b
  Less than or equal to TRUE if $a is less than or
  equal to $b.
• $a >= $b
  Greater than or equal to TRUE if $a is greater than
  or equal to $b.
          Logical Operators
• $a and $b
  TRUE if both $a and $b are TRUE.
• $a or $b
  TRUE if either $a or $b is TRUE.
• $a xor $b
  TRUE if either $a or $b is TRUE, but not
  both.
• ! $a
  TRUE if $a is not TRUE
       Execution Operators
 backticks (``) operator will attempt to
execute the contents of the backticks as a
shell command.

Note: backticks are not single-quotes!
       Execution Operators
<?php
 $output = `dir`;
echo "<pre>$output</pre>";
?>

 Executes dir command and print its output.
 isn‟t that cool?
       Incrementing/Decrementing
               Operators
    PHP supports C-style pre- and post-
    increment and decrement operators

•   Pre-increment
•   Post-increment
•   Pre-decrement
•   Post-decrement
                    Examples
 ++$a
Increments $a by one, then returns $a.

$a++
Returns $a, then increments $a by one.

- - $a
Decrements $a by one, then returns $a.

$a - -
Returns $a, then decrements $a by one.
             More examples
<?php
echo "<h3>Postincrement</h3>";
$a = 5;
echo "Should be 5: " . $a++ . "<br />\n";
echo "Should be 6: " . $a . "<br />\n";

echo "<h3>Preincrement</h3>";
$a = 5;
echo "Should be 6: " . ++$a . "<br />\n";
echo "Should be 6: " . $a . "<br />\n";
?>
              String Operators
There are two string operators
• concatenation operator ('.')
• concatenating assignment operator ('.=')

Example:

<?php
$a = "Hello ";
$b = $a . "World!"; // now $b contains "Hello World!"

$a = "Hello ";
$a .= "World!";   // now $a contains "Hello World!"
?>
             Array Operator
• $a + $b Union of $a and $b.
• $a == $b TRUE if $a and $b have the same
  key/value pairs.
• $a === $b TRUE if $a and $b have the same
  key/value pairs in the same order and of the
  same types.
• $a != $b TRUE if $a is not equal to $b.
• $a <> $b TRUE if $a is not equal to $b.
• $a !== $b TRUE if $a is not identical to $b
           Type Operators
• PHP has one type operator ` instanceof `
  is used to determine whether a given
  object is of a specified object class.


       details discussion in OOP Session 
               Control Structure
•   if                 •   switch
•   else               •   declare
                       •   return
•   elseif
                       •   require()
•   while
                       •   include()
•   do-while           •   require_once()
•   for                •   include_once()
•   foreach
•   break
•   continue
                   foreach
foreach gives an easy way to iterate over arrays


       <?php
       $num = array(1, 2, 3, 4);
       foreach ($num as $value) {
         $value = $value * 2;
         echo $value;
       }
       ?>
                         Switch
 Syntax similar to C, but one major difference is you can
 use string in case, take a look.

<?php
  switch ($i) {
  case "apple":
    echo "i is apple";
    break;
  case "bar":
    echo "i is bar";
    break;
  case "cake":
    echo "i is cake";
    break;
    default: break;
  }
  ?>
                declare
• Will be discussed in “PHP and the Web”
  Section.
         include / require
like C/C++ #include, This include(..) and
require(..) statement includes and
evaluates the specified file.

example in next slide >>
  test1.php                     test2.php

<?php                       <?php
 $i=1;                       $j=10;
 echo “from test1.php”       echo “from test2.php
?>                          ?>

                     main.php


               <?php
               Include(“test1.php”);
               require(“test2.php”);
               echo $i;
               echo $j;
               ?>
 require_once / include_once
require_once and include_once behavior
is similar to the require() statement, with
the only difference being that if the code
from a file has already been included, it
will not be included again.

it is good practice to use include_once to
avoid collision problem.
  test1.php                          test2.php

<?php                            <?php
  include(“test2.php”);          $j=10;
 $i=1;                             echo “from test2.php
 echo “from test1.php”           ?>
?>
                          main.php

                  <?php
                  Include_once(“test1.php”);
                  require_once(“test2.php”);
                  echo $i;
                  echo $j;
                  ?>
Functions in PHP
                    Functions
   User defined function syntax :



function foo($arg_1, $arg_2, /* ..., */ $arg_n)
{
  echo "Example function.\n";
  return $retval;
}
          Declaring a function
<?php
 function foo($k,$j)
 {
  echo "I don't exist until program execution
   reaches me.\n";
  $t = $k*$j;
  return $t;
 }
?>
            Calling user function
<?
foo(2,3);

function foo($t,$k)
{
 …..
return true;
}
?>
 Passing Arguments to Functions

function page_header2($color)
{
print '<html><head><title>Welcome to my
  site</title></head>'; print '<body
  bgcolor="#' . $color . '">';
}

page_header2('cc00cc');
    Specifying a default value
 function page_header3($color = 'cc3399')
 {
    print '<html><head><title>Welcome to my
   site</title></head>';
    print '<body bgcolor="#' . $color . '">';
}
 Defining a two-argument function
 function page_header4($color, $title)
{
print '<html><head><title>Welcome to ' .
   $title . '</title></head>';
print '<body bgcolor="#' . $color . '">';
}

// Contd.
Calling a two-argument function
page_header4('66cc66','my homepage');
    Multiple optional arguments
<?
 function page ($color, $title, $header = 'Welcome')
{
print '<html><head><title>Welcome to ' . $title .
   '</title></head>'; print '<body bgcolor="#' . $color . '">';
print "<h1>$header</h1>";
}

 page ('66cc99','my wonderful page');
 page ('66cc99','my wonderful page','This page is great!');
?>
      Changing argument values
<?
function countdown($top)
{
while ($top > 0) {
print "$top.."; $top--;
}
print "boom!\n";

}

$counter = 5;
countdown($counter);
print "Now, counter is $counter";
?>

//what is the value of the $counter variable?
      Function inside Function
function foo()
  {
    function bar()
    {
     echo "I don't exist until foo() is called.\n";
    }
  }
                  Function Practice
<?
function page_header( )
 {
print '<html><head><title>Welcome to my site</title></head>';
   print '<body bgcolor="#ffffff">';
}
page_header( );
print "Welcome, $user";

page_footer( );

function page_footer( )
{
print '<hr>Thanks for visiting.'; print '</body></html>';
}
?>
            Variable Scope
Local Variable

Variable declare inside the function are
called local variable. They are completely
separate from a variable that happens to
have the same name in another function.

Example::
<?                         $t is local variable
$t = 3;                    of function foo
function foo()
{
  $t=23;
}

foo();
                       $t global variable
echo $t;
?>

Output?... 3 .. Why?
      Accessing Global Variable from Function
<?
$t = 3;
function foo()
                              Foo function now
{
                              using $t as global
global $t;
$t=23;
                              Variables because $t
}                             is declared
                              as global and now it
foo();                        points to global space.
echo $t;
?>

• Output?... 23 .. Why?
Remember C‟s extern
          PHP References
A variable that "references" the contents of
another variable. PHP references serve the
same purpose as a memory pointer in a C-
style language.
           PHP Reference
$foo = 5;
$bar = $foo;




 $foo and $bar as independent variables
           PHP Reference
$foo = 5;
$bar = & $foo;




 $bar as a reference to the variable $foo
         Check this out!
<?php
$foo = 5;
$bar = & $foo
$bar = 10;
echo $foo;
?>
          Why Reference?
• It reduces the memory consumption of
  your PHP applications

• Performance Improvements
            Variable Variable

<?
$a = 100;
$b = „a‟;
echo $$b;
?>

Guess the output? And discuss
          Variable Function
PHP variable functions. This means that if a
variable name has parentheses appended to
it, PHP will look for a function.

            Take a look one example
               Example # 1
<?
function foo($name)
{
echo “hi $name, I am foo function”;
}

$a=“foo”;

$a(“chris”);
?>
                   Example #2

<?
function odd_number ($x) {
echo “$x is odd”;
}

function even_number ($x) {
echo “$x is even”;
}
$n = 15;
$a = ($n % 2 ? „odd_number‟ : „even_number‟);
$a($n);
                Practice!
<?php
function restaurant_check($meal, $tax, $tip)
{
  $tax_amount = $meal * ($tax / 100);
  $tip_amount = $meal * ($tip / 100);
  $total_amount = $meal + $tax_amount +
   $tip_amount;
  return $total_amount;
}
?>           // contd…
$total = restaurant_check(15.22, 8.25, 15);
print 'I only have $20 in cash, so...';
if ($total > 20) {
   print "I must pay with my credit card.";
}
else {
print "I can pay with cash.";
}
• Next 2 session –

   Object-Oriented PHP

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:2
posted:10/4/2011
language:English
pages:77