Chapter 2
Chapter 2
Chapter 2
PHP
Companies that Use PHP
Contents
Basics of PHP
Control structure
Function
Array
Classes
Objects
Members (Data & Function)
Inheritance, Encapsulation, Abstraction and
Polymorphism
Introduction to PHP
• PHP-Hypertext Preprocessor.
• Is a server-side scripting language.
– Capable of generating the HTML pages
<?php
$name= 'Bob';
$Name= 'Joe';
Echo "$name, $Name"; //outputs "Bob, Joe"
$4site = 'not yet'; // invalid; starts with a number
$_4site = 'not yet'; //valid; starts with an underscore
cont’d
1. Function isset tests if a variable is assigned or not
$A = 1;
if (isset($A))
print “A isset” if (!
isset($B))
print “B is NOT
set”;
2. Using $$
$help = “hiddenVar”;
$$help = “hidden
Value”;
echo $$help; // prints
hidden Value
20
$$help = 10;
cont’d
• Character escaping
– If the string is enclosed in double-quotes ("),
PHP understands more escape sequences for
special characters:
sequence meaning
\n linefeed
\r carriage return
\t horizontal tab
\\ backslash
\$ dollar sign
\" double-quote
21
Variable scope
PHP has four different scopes:
– Local: a variable declared within a PHP function
– global: a variable that is defined outside of any
function
• To access a global variable from within a function,
use the global keyword
– Static: when a function is completed, all of its
variables are normally deleted.
• However, sometimes you want a local variable to
not be deleted.
• To do this, use static keyword
– Parameter: is a local variable whose value is
passed
the function by the calling code
• E.g. Function($X)
22
Cont…
• Several predefined variables in PHP are
"superglobals", which means that they are always
accessible, regardless of scope - and you can access
them from any function, class or file without having
to do anything special.
• The PHP superglobal variables are:
$GLOBALS
$_SERVER
$_REQUEST
$_POST
$_GET
$_FILES
$_ENV
$_COOKIE
$_SESSION
23
Example
//local //Global // static
<?php <?php <?php
$x = 5; $x = 5; function myTest() {
$y = 10;
$y = 10; static $x = 0;
function myTest() { echo $x;
function myTest() {
$x=4, $y=6; $GLOBALS['y'] = $x++;
$y = $x + $y; $GLOBALS['x'] + }
echo $y; $GLOBALS['y']; myTest();
} } myTest();
myTest(); myTest();
myTest();
echo $y; // echo $y; // outputs 15 ?>
outputs
?> 10 ?> //outputs
012
24
PHP String Variables
• A string variable is used to store and manipulate text.
• String variables are used for values that contain
characters.
A string can be used directly in a function or it can be
stored in a variable.
• Below, the PHP script assigns the text "Hello World"
to a string variable called $txt:
<?php
$txt="Hello World";
echo $txt;
?>
The output of the code above will be: Hello World
25
Cont’d
Variables within double quoted strings (“”) are parsed
Example
$name = “Abebe”;
$message = “Hello $name”;
echo $message; //Hello Abebe
Variables within single quoted strings (‘’) are not
parsed!
Example
$name = “Abebe”;
$message = ‘Hello $name’;
echo $message; //Hello $name
Cont’d
Variable parsing – variables within double quoted
strings are parsed.
Example
<?php
$beer = 'Heineken';
echo "$beer's taste is great"; // works
echo "He drank some $beers"; // won't work
echo "He drank some ${beer}s"; // works
echo "He drank some {$beer}s"; // works
?>
“ or ‘
Difference between strings written in single and
double quotes:
In a double-quoted string any variable names are
expanded to their values.
In a single-quoted string, no variable expansion takes
place. <?php
$name = ‘Phil’;
<?php $age = 23;
$name = ‘Phil’; echo ‘$name is $age’;
$age = 23; // $name is $age
echo “$name is $age”; ?>
// Phil is 23
?>
Concatenation
Use a period/ dot (.) to join strings into one
<?php
$string1=“Hello”;
$string2=“PHP”;
$string3=$string1 . “ ” . $string2;
print $string3;
?>
Hello PHP
Output
There are two language constructs available to display data:
print() and echo()
They can be used with or without brackets
Note that the data ‘displayed’ by PHP is actually parsed by
your browser as HTML
<?php
echo ‘Hello World!<br>’;
echo(‘Hello World!<br>’);
print ‘Hello World!<br>’;
print(‘Hello World!<br>’);
?>
Echo example
<?php
$foo = 25; // Numerical variable
$bar = “Hello”; // String variable
echo $bar; // Outputs Hello
echo $foo,$bar; // Outputs 25Hello
echo “5x5=”,$foo; // Outputs 5x5=25
echo “5x5=$foo”; // Outputs 5x5=25
echo ‘5x5=$foo’; // Outputs 5x5=$foo
?>
Notice how echo ‘5x5=$foo’ outputs $foo rather than replacing it
with 25
Strings in single quotes (‘ ’) are not interpreted or evaluated by PHP.
This is true for both variables and character escape-sequences (such
as “\n” or “\\”)
PHP Forms
Input to server side scripts comes from clients through
forms
Two methods of sending data: GET & POST
GET
• Search queries and small amounts of data
• Also generated when a user clicks on a link
• Non secure (displayed in address bar)
POST
• Large and secure data
The default method for HTML forms is GET
To access form field values in PHP, use the built-in PHP
arrays: $_GET and $_POST respectively for GET and POST
request methods
Cont’d
The names of the form fields will be used as indices in the
respective arrays
For example, to access the value of an input box named
‘first_name’ in a form whose method is POST, write:
$_POST[ ‘first_name’ ]
If the form method is GET,
$_GET[ ‘first_name’ ]
Example:
<form method=‘POST’ action=“login.php”>
<input type=‘text’ name=‘username’><br>
<input type=‘password’
name=‘password’><br>
<input type=‘submit’ value=‘login’>
</form>
Cont’d
//login.php
<?php
$username = $_POST[ ‘username’ ];
$password = $_POST[ ‘password’ ];
if($username == “user” && $password == “pass”){
//login successful
header( ‘Location: home.php’ );
exit();
}else{//login failed
header( ‘Location: login.html’ );
exit();
}
} ?>
PHP Form Handling
• The PHP superglobals $_GET and $_POST are used to
collect form-data.
• GET vs. POST
– Both GET and POST create an array (e.g. array( key =>
value, key2 => value2, key3 => value3, ...)). This array
holds key/value pairs, where keys are the names of the
form controls and values are the input data from the
user.
– Both GET and POST are treated as $_GET and $_POST.
Cont’d
These are superglobals, which means that they are
always
accessible, regardless of scope - and you can access
them from any function, class or file without having to
do anything special.
– $_GET is an array of variables passed to the current
script via the URL parameters.
– $_POST is an array of variables passed to the current
script via the HTTP POST method.
When to use GET?
• Information sent from a form with the GET method is
visible to everyone (all variable names and values are
displayed in the URL).
• GET also has limits on the amount of information to send.
• The limitation is about 2000 characters. However,
because the variables are displayed in the URL, it is
possible to bookmark the page. This can be useful in some
cases.
• GET may be used for sending non-sensitive data.
• Note: GET should NEVER be used for sending
passwords or other sensitive information!
When to use POST?
• Information sent from a form with the POST method
is invisible to others (all names/values are embedded
within the body of the HTTP request)
• Has no limits on the amount of information to send.
• POST supports advanced functionality such as
support for multi-part binary input while
uploading files to server.
• However, because the variables are not
displayed in the URL, it is not possible to
bookmark the page.
• Developers prefer POST for sending form data.
Example
<--! welcome.php -->
<html>
<--! <--! indexget.html-->
<body>
indexpost.html-- <html>
Welcome <?php echo
<body>
> <form
$_POST["name"]; ?><br>
Your email address is:
<html> action="welcome_get.php"
<?php echo
method="get">
<body> Name: <input type="text"
$_POST["email"]; ?>
<form name="name"><br> </body>
action="welcom E-mail: <input </html>
e.php" <--!welcome_get.php
type="text" <html>
method="post"> name="email"><br> <body>
Name: <input <input type="submit"> Welcome <?php echo
type="text" $_GET["name"]; ?><br>
</form>
name="name">< Your email address is:
br> <?php echo
</body>
$_GET["email"]; ?>
E-mail: <input </html> </body>
type="text" </html>
Post Output
The page directed to welcome.php when the user clicks submit query button
Get Output
Shows username and email on URL
indexget.html
The page directed to welcome_get.php when the user clicks submit query
button
Cont’d
In effect, all form data will be available to PHP scripts
through the appropriate array: $_GET or $_POST
Another way of getting input from client can be using
cookies
Cookie is information stored on the client by the server
Cookies stored on a client associated to a particular
server are sent to the server every time that same client
computer requests for a page
Cookies are often used to identify a user
Cont’d
To create a cookies, use the setcookie() function
Cookies must be sent before any output from your
script.
This function must be called before any other output in
the PHP file, i.e before <html>, any spaces, …
To retrieve a cookie value, use the $_COOKIE array
with the name of the cookie as index
<html><body>
<?php if( isset( $_COOKIE[ “uname” ] ) )
echo “Welcome “ . $_COOKIE[ “uname” ] . “! <br> “;
else
echo “Cookie not set <br>”;
?>
Operators
Arithmetic
+, -, *, /, %, --, ++
Assignment (simple, compound)
=, +=, -=, *=, /=, %=
Comparison
==, != , ===, !==, <, >, <=, >=
Logical
&&, || , !
String
. (dot)
Arithmetic Operators
<html><body>
<?php
switch ($x)
{
case 1:
echo "Number 1";
break;
case 2:
echo "Number 2";
break; Next slide
Cont…
case 3:
echo "Number 3"; break;
default:
echo "No number between 1 and 3";
}
?>
</body>
</html>
Cont’d
Break
ends execution of the current for, for-each, while, do-while, or
switch structure
Continue
used within looping structures to skip the rest of the current loop
iteration
Return
If called from within a function, the return statement immediately
ends execution of the current function, and returns its argument
as the value of the function call
Loops in PHP
‘For’ Loop
for(var=initial;condition;incr/decr)
{
statements;
}
‘While’ Loop
while (condition)
{
statements;
}
Cont’d
‘Do….While’ Loop
do{
statements;
}
while (condition);
echo $cars[0][2];// 18
echo $cars[1][1];// 15
Classes in PHP
A class is a template/ blueprint for objects.
A class is defined by using the class keyword,
followed by the name of the class and a pair of curly
braces ({}).
All its properties and methods go inside the braces.
<?php
class Fruit {
// code goes here...
}?>
Class Example
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}}
?>
What is an Object?
An object is a thing, anything, just as things in the
real world.
o E.g. (cars, dogs, money, books, … )
In the web browser, objects are the browser window
itself, forms, buttons, text boxes, …
Methods are things that objects can do.
◦ Cars can move, dogs can bark.
◦ Window object can alert the user “alert()”.
All objects have properties.
◦ Cars have wheels, dogs have fur.
◦ Browser has a name and version number.
Example of an Object
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
$apple = new Fruit();
$banana = new Fruit();
$apple->set_name('Apple');
$banana->set_name('Banana');
echo $apple->get_name();
echo "<br>";
echo $banana->get_name();
?>
PHP Functions
Syntax
function functionName()
//code to be executed;
}
Cont…
A simple function that writes my name when it is called:
<html><body>
<?php
function writeName()
{
echo "Jemal Hailu";
}
echo "My name is ";
writeName(); // function calling
?>
</body></html>
{
echo $fname . " Refsnes.<br />";
}
echo "My name is "; writeName("Kai
Jim"); Output:
echo "My sister's name is ";
writeName("Hege"); My name is Kai Jim Refsnes.
echo "My brother's name is "; My sister's name is Hege Refsnes.
writeName("Stale"); My brother's name is Stale Refsnes.
?>
</body>
Cont…
Return values
To let a function return a value, use the return statement.
<html>
<body>
<?php
function add($x,$y)
{
$total=$x+$y;
return $total;
}
echo "1 + 16 = " . add(1,16);
?>
</body>
</html>
Output: 1 + 16 = 17
Cont…
Passing by value
function salestax($price,$tax){
$total=$price + ($price*$tax);
echo” Total cost:$total”;
}
salestax($42,$0);
<?php
$cost = 20.00;
$tax = 0.05;
function calculate_cost(&$cost, $tax)
{
// Modify the $cost variable Output:
$cost = $cost + ($cost * $tax); Tax is 5%
// Perform some random change to the $tax var Cost is $21
$tax += 4;
}
calculate_cost($cost,$tax);
echo "Tax is: ". $tax*100; echo "Cost is: $". $cost;
?>
Predefined functions
Arithmetic functions
floor, ceil, round, abs, min, max, rand, etc.
String functions
strlen, strcmp, strpos, substr, strtolower, strtoupper
chop – remove whitespace from the right end
trim – remove whitespace from both ends
ltrim – remove whitespace from the left end
strlen() function
The strlen() function is used to return the length of
a string.
Let's find the length of a string:
<?php
echo strlen("Hello world!");
?>
The output of the code above will be: 12
4 Pillars for OOP
1. Abstraction
Abstraction is the process of showing only
essential/necessary features of an entity/object to the
outside world and hide the other irrelevant information.
For example to open your TV we only have a power
button, It is not required to understand how infra-red waves
are getting generated in TV remote control.
Cont…
2. Encapsulation
Encapsulation means wrapping up data and member
function together into a single unit i.e. class.
Encapsulation is a protection mechanism for the data
members and methods present inside the class.
Encapsulation automatically achieves the concept of data
hiding providing security to data by making the variable
private and exposing the property to access the private data
which would be public.
Cont…
3. Inheritance
The ability of a class to derive or inherit the properties and
characteristics from another class is called inheritance.
Inheritance is when an object acquires the property of
another object.
Inheritance allows a class (subclass) to acquire the
properties and behavior of another class (super-class).
It helps to reuse, customize and enhance the existing code.
Cont…
So it helps to write a code accurately and reduce the
development time.
Using the term extends, we inherit the characteristic of a
parent class.
Syntax:
Class ChildClass extends ParentClass
In the above syntax, ChildClass is a derived class (also
called extended class and subclass) that extends
ParentClass (also called superclass and base class).
Cont…
4. Polymorphism
polymorphism means "many forms".
A subclass can define its own unique behavior and still
share the same functionalities or behavior of its
parent/base class.
A subclass can have their own behavior and share some of
its behavior from its parent class not the other way around.
A parent class cannot have the behavior of its subclass.
Cont…
Polymorphism is essentially an OOP pattern that enables
numerous classes with different functionalities to execute
or share a common Interface.
The usefulness of polymorphism is code written in
different classes doesn't have any effect which class it
belongs because they are used in the same way.
<?php // Polymorphism Example
interface Machine {
public function calcTask(); }
class Circle implements Machine {
private $radius; public function __construct($radius)
{
$this -> radius = $radius;
}
public function calcTask(){
return $this -> radius * $this -> radius * pi(); } }
class Rectangle implements Machine {
private $width; private $height;
public function __construct($width, $height){
$this -> width = $width; $this -> height = $height;
}
public function calcTask(){
return $this -> width * $this -> height;} }
$mycirc = new Circle(3);
$myrect = new Rectangle(3,4);
echo $mycirc->calcTask(); Output : 28.274
echo $myrect->calcTask(); 12
?>
Any Question?