Introduction to PHP - Departamento de Lenguajes y Sistemas

Anuncio
Tiempo: 2h
Introduction to PHP
(PHP: Hypertext Preprocessor)
Departamento de
Lenguajes y Sistemas Informáticos
Applied Software Engineering Group
November 2010
[Ángel US V7] Diseño: Amador Durán Toro (2003-2006)
Versión original: Amador Durán Toro y David Benavides (diciembre 2006)
Última revisión: José An tonio Parejo, adaptación a PHP y traducción.
escuela técnica superior
de ingeniería informática
[Ángel US V7] Diseño: Amador Durán Toro (2003-2006)
Introduction to PHP
• Server Processing
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
PHP
1. Introduction
PDO
2. The PHP Language
1. Comments
2. Types
5. Control flow
structures
6. Classes and
objects
7. Predefined
classes
3. PHP programming
styles
Web client
8
2
7
4
3
Data
1
Business Logic
4. Functions
Presentation
3. Variables
6
DBMS
5
Web server
(with processing capabilities)
Sevilla, noviembre de 2010
Grupo de Ingeniería del
1
[Ángel US V7] Diseño: Amador Durán Toro (2003-2006)
Introduction to PHP
• Basic Concepts
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
1. Introduction
2. The PHP Language
1. Comments
2. Types
3. Variables
4. Functions
5. Control flow
structures
6. Classes and
objects
7. Predefined
classes
3. PHP programming
styles
– PHP = Personal Home Page
PHP: Hipertext Preprocessor
– PHP is a language that allows creating scripts that
are interpeted at server, creating content that is
sent to the client.
– PHP is neither standard nor has a formal
specification, but is a widely accepted Open Source
technology.
– The pages must have the extension .php, otherwise
the server does not process the PHP code
– A PHP page can not be properly opened as file. It
must be done by means of a web server (usually
Apache), usually as:
• http://localhost/…/archivo.php
• http://127.0.0.1/…/archivo.php
• http://nombre_máquina/…/archivo.php
• http://dirección IP/…/archivo.php
Sevilla, noviembre de 2010
Grupo de Ingeniería del
2
[Ángel US V7] Diseño: Amador Durán Toro (2003-2006)
Introduction to PHP
• Un poco de Historia de PHP:
Año
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
1. Introduction
Versión
1995
PHP 1.0
Set of simple scripts written in Perl by Rasmus
Lerdorf. Latter it were rewritten in C providing
DB access capabilities.
1997
PHP 2.0
Set of scripts in beta state .
1998
PHP 3.0
2000
PHP 4.0
Performance improvements, modularity more DB
Support and third party.
2004
PHP 5.0
New object model, performance improvements
?
PHP 6.0
Unicode support, namespaces, closures (this
2 last features were present in v5.3)
2. The PHP Language
1. Comments
2. Types
3. Variables
4. Functions
5. Control flow
structures
6. Classes and
objects
3. PHP programming
styles
Sevilla, noviembre de 2010
Grupo de Ingeniería del
Time
7. Predefined
classes
Características
It was the first version similar to current PHP,
full rewrite by Andi Gutmans and Zeev Suraski.
It included a stronger syntax and mimimal OO
support.
3
[Ángel US V7] Diseño: Amador Durán Toro (2003-2006)
Introduction to PHP
• Usage of PHP:
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
1. Introduction
2. The PHP Language
1. Comments
2. Types
3. Variables
4. Functions
5. Control flow
structures
6. Classes and
objects
7. Predefined
classes
3. PHP programming
styles
http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html
Sevilla, noviembre de 2010
Grupo de Ingeniería del
4
[Ángel US V7] Diseño: Amador Durán Toro (2003-2006)
Introduction to PHP
• PHP Objects
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
1. Introduction
2. The PHP Language
1. Comments
2. Types
3. Variables
4. Functions
5. Control flow
structures
6. Classes and
objects
7. Predefined
classes
3. PHP programming
styles
– Predefined classes, variables and functions of PHP
and data access objects (PDO) are the elements of
the language that we will use most frequently.
– Predefined PHP variables are always available in
PHP code, namely: $GLOBALS, $_SESSION,
$_REQUEST,$_GET, $_POST, $_FILES, $_COOKIE,
$_SERVER, $_ENV.
– PHP incorporates a garbage collector, so we must
not destroy objects explicitly. However we must
create destructors if we use blocking resources,
such as DB connections, printers or files.
• PDO Objects
– PDO objects must be created explicitly (as all
ordinary PHP objects) using new.
– We will use PHP pages to process data form sent
forms, access a database and returns a response to
user.
Sevilla, noviembre de 2010
Grupo de Ingeniería del
5
[Ángel US V7] Diseño: Amador Durán Toro (2003-2006)
Introduction to PHP
• Structure of an PHP page
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
1. Introduction
2. The PHP Language
1. Comments
2. Types
3. Variables
4. Functions
5. Control flow
structures
6. Classes and
objects
7. Predefined
classes
3. PHP programming
styles
<html>
<!– HTML code -->
…
<?php PHP code ?>
…
<!– HTML code -->
…
<script language=“php” %>
PHP code
</script>
…
<!– HTML code -->
</html>
• Moreover we can use :
<? … ?> <% … %>
Sevilla, noviembre de 2006
Grupo de Ingeniería del
6
[Ángel US V7] Diseño: Amador Durán Toro (2003-2006)
Introduction to PHP
• Main features of PHP:
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
1. Introduction
2. The PHP Language
– Is an interpreted languge (script, not compiled)
– Is an Object based language
– Syntax similar to C and Java
1. Comments
2. Types
3. Variables
4. Functions
5. Control flow
structures
6. Classes and
objects
7. Predefined
classes
3. PHP programming
styles
Sevilla, noviembre de 2010
Grupo de Ingeniería del
7
[Ángel US V7] Diseño: Amador Durán Toro (2003-2006)
Introduction to PHP
• Comments:
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
1. Introduction
2. The PHP Language
1. Comments
// C-stlye Comment
# Shell-style Comment
/* Multi-line Java-style comment
*/
2. Types
3. Variables
4. Functions
5. Control flow
structures
6. Classes and
objects
7. Predefined
classes
3. PHP programming
styles
Sevilla, noviembre de 2010
Grupo de Ingeniería del
8
[Ángel US V7] Diseño: Amador Durán Toro (2003-2006)
Introduction to PHP
• PHP is weakly typed language
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
1. Introduction
2. The PHP Language
1. Comments
2. Types
3. Variables
4. Functions
5. Control flow
structures
6. Classes and
objects
7. Predefined
classes
3. PHP programming
styles
• Basic PHP types
– Strings: "¡Hello world!", „john@rambo.com'
– Numbers: 12, 22.4, -5
– Boolean: true, false
• Constant String
$alive
$alive
$alive
$alive
$alive
=
=
=
=
=
false; // $alive is false.
1; //$alive is true.
-1; //$alive is true.
5; //$alive is true.
0; //$alive is false.
– „¿Can I write <h1>HTML</h1>?'
– “¿Can I use this symbol: \\ ?“
• PHP casts types automatically:
$total = 5; // integer
$count = "15"; // string
$total += $count; // $total = 20 (integer)
• In PHP you can cast explicitly :
Sevilla, noviembre de 2010
Grupo de Ingeniería del
9
[Ángel US V7] Diseño: Amador Durán Toro (2003-2006)
Introduction to PHP
• PHP operators:
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
1. Introduction
2. The PHP Language
1. Comments
2. Types
3. Variables
4. Functions
5. Control flow
structures
6. Classes and
objects
– Boolean: and Ξ &&, or Ξ ||, !, xor, ==, !=
– Numbers: +,-,*,/,%, ==,!=, <, >. >=, <=,++,--
– Identity operator ===
True if == and operands has
the same type
– Operator ‟.‟ to append strings, you can also use ‟.=‟
7. Predefined
classes
3. PHP programming
styles
Sevilla, noviembre de 2010
Grupo de Ingeniería del Software
• echo y print are considered basic language
constructs that allow print the value of PHP
expression on the output (our web page).
10
[Ángel US V7] Diseño: Amador Durán Toro (2003-2006)
Introduction to PHP
•
Our first php program:
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
1. Introduction
2. The PHP Language
1. Comments
2. Types
3. Variables
4. Functions
5. Control flow
structures
6. Classes and
objects
7. Predefined
classes
3. PHP programming
styles
Sevilla, noviembre de 2010
Grupo de Ingeniería del Software
<!DOCTYPE …
<html>
<head>
<title> Hola mundo con PHP</title>
</head>
<body>
<?
print(“<p>Hello world</p>\n”);
phpinfo();
?>
</body>
</html>
11
[Ángel US V7] Diseño: Amador Durán Toro (2003-2006)
Introduction to PHP
• PHP variables:
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
1. Introduction
2. The PHP Language
1. Comments
2. Types
3. Variables
4. Functions
5. Control flow
structures
6. Classes and
objects
7. Predefined
classes
3. PHP programming
styles
– PHP variable being with „$‟.
– PHP is case-sensitive concerning to variable names
– In PHP variables can be used without an explicit
declaration, moreover they can not be explictly
declared
$ABDscore = 10;
– PHP automatically replaces variable names by
values on strings (only when using “ “ “):
$name = “José Antonio";
echo "Hello, $name";
Sevilla, noviembre de 2010
Grupo de Ingeniería del Software
Hello José Antonio
12
[Ángel US V7] Diseño: Amador Durán Toro (2003-2006)
Introduction to PHP
• PHP Arrays:
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
1. Introduction
2. The PHP Language
1. Comments
2. Types
3. Variables
4. Functions
5. Control flow
structures
6. Classes and
objects
7. Predefined
classes
3. PHP programming
styles
– In PHP arrays can contain objects of different
types.
– PHP uses associative arrays, where for each
value we have a unique key (that can be a
string, number , object, …).
– The operator used to obtain the value using
the key is [] : “$array[key]”.
$states =array(0 => “ Alabama”, 1 => “ Alaska”,…);
$echo $states[0];
– Arrays can be used without initialization nor
declaration arrays
$states[0]= “Washington”;
$states[1]=“New York ”,
…
$echo $states[0];
Sevilla, noviembre de 2006
Grupo de Ingeniería del
13
[Ángel US V7] Diseño: Amador Durán Toro (2003-2006)
Introduction to PHP
• PHP Arrays :
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
1. Introduction
2. The PHP Language
1. Comments
2. Types
3. Variables
4. Functions
5. Control flow
structures
6. Classes and
objects
7. Predefined
classes
3. PHP programming
styles
– PHP provides the function extract to expose the
elements of an array as variables
$shapes=array(„coke' => „Cilinder', „orange' => „sphere„);
extract($shapes);
// $coke and $orange are now variables
echo $coke;
echo "<br>";
echo $orange;
– Interesting functions to deal with arrays:
• Array_push(array, elements)
• Array_pop(array)
• Array_unshift( array,elements)
• Array_shift( array)
• Array_merge( array1,array2)
• Array_keys( array)
• Array_values( array)
• Shuffle( array)
Sevilla, noviembre de 2006
Grupo de Ingeniería del
14
[Ángel US V7] Diseño: Amador Durán Toro (2003-2006)
Introduction to PHP
• PHP functions:
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
1. Introduction
2. The PHP Language
1. Comments
2. Types
3. Variables
4. Functions
function name( arguments ) // each argument use $
{
$local = initial_value;
// fuction code
return (expression);
}
5. Control flow
structures
6. Classes and
objects
7. Predefined
classes
– If return is not performed a value of NULL is
considered as the result of the function.
3. PHP programming
styles
Sevilla, noviembre de 2010
Grupo de Ingeniería del
15
[Ángel US V7] Diseño: Amador Durán Toro (2003-2006)
Introduction to PHP
• Some interesting PHP functions:
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
1. Introduction
2. The PHP Language
1. Comments
2. Types
3. Variables
4. Functions
– Working with Strings:
• printf(string,…):string formatting
• strlen(string): returns the length of the string
• Strtoupper(string) y strtolower(string)
• Strstr(str1,str2 ):tests if str1 is substring of str2
• substr(string, position): obtain a substring
5. Control flow
structures
6. Classes and
objects
7. Predefined
classes
3. PHP programming
styles
– Date & Time treatment:
• time():current instant
• date(“format”, variable): allows date formatting
<?
echo date("m/d/y G.i:s",$timestamp);
?>
• checkdate(m,d, y): test if date is valid
• mktime(h,m,s,month,day,year):creates a new date
• You can add or substract seconds to dates as integers
Sevilla, noviembre de 2010
Grupo de Ingeniería del Software
16
[Ángel US V7] Diseño: Amador Durán Toro (2003-2006)
Introduction to PHP
• Some interesting PHP functions:
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
– Usage of HTTP headers:
• Header(string): takes as argument the header to
sent. enviar.
1. Introduction
be
2. The PHP Language
1. Comments
<?php
2. Types
// Usage of headers to perform redirection
Header( “Location: http://www.us.es”);
3. Variables
4. Functions
5. Control flow
structures
?>
6. Classes and
objects
You must have in to account
that Headers can´t be sent
after any part of the page
content
7. Predefined
classes
3. PHP programming
styles
<html>
…
<? Header( “Location: http://www.us.es”); ?>
</html >
Sevilla, noviembre de 2010
Grupo de Ingeniería del Software
17
[Ángel US V7] Diseño: Amador Durán Toro (2003-2006)
Introduction to PHP
• PHP control flow structures:
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
1. Introduction
2. The PHP Language
1. Comments
2. Types
3. Variables
4. Functions
– As in Java and C++.
if (expression) {
// …
}
else {
// …
}
5. Control flow
structures
6. Classes and
objects
7. Predefined
classes
3. PHP programming
styles
while (condición) {
//…
}
do {
// …
} while (expression)
foreach($X as $Y){
// using arrays
}
Sevilla, noviembre de 2010
Grupo de Ingeniería del Software
switch (expression) {
case label1 :
// block1
break;
case label2 :
// block2
break;
...
default :
// block n
}
for ($i=0; $i<=$N; $i=$i+1) {
// …
}
foreach($X as $Y => $Z){
/* using $Y as key and
$Z as value of each
element of $X */
}
18
[Ángel US V7] Diseño: Amador Durán Toro (2003-2006)
Introduction to PHP
• PHP supports OO programming
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
1. Introduction
2. The PHP Language
1. Comments
2. Types
3. Variables
4. Functions
• Classes can be defined in PHP using the following
sintax:
<?php
class Persona
{
// member declaration
public $name = ‟My name';
5. Control flow
structures
// method declaration
public function showName() {
echo $this->name;
}
6. Classes and
objects
7. Predefined
classes
3. PHP programming
styles
}
?>
– public/protected/private: allows to define the visibility of
properties and methods.
– $this: avaliable when a method in invoked on an object, it
references the instance of the object invoked..
Sevilla, noviembre de 2010
Grupo de Ingeniería del Software
19
[Ángel US V7] Diseño: Amador Durán Toro (2003-2006)
Introduction to PHP
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
• In PHP objects are created using the new
operator
• PHP allows declaring constructors and desturctors
1. Introduction
2. The PHP Language
1. Comments
2. Types
3. Variables
4. Functions
<?php
class MiClass {
function __construct() {
print “Constructing\n";
}
5. Control flow
structures
6. Classes and
objects
7. Predefined
classes
3. PHP programming
styles
}
function __destruct() {
print ”Destroying\n";
}
$obj = new MiClass ();
?>
• PHP incorporates a garbagge collector so that the
destructor is invoked automatically when the
object is out of scope.
Sevilla, noviembre de 2010
Grupo de Ingeniería del Software
20
[Ángel US V7] Diseño: Amador Durán Toro (2003-2006)
Introduction to PHP
• Moreover PHP allows inheritance and Polimorfism:
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
1. Introduction
2. The PHP Language
<?php
class Student extends Person
{
// member declaration
public $courses= array(„ABD‟,‟DBD‟);
1. Comments
protected $scores=array(8,5);
2. Types
3. Variables
// method declaration
public function showScores() {
4. Functions
5. Control flow
structures
echo $this->name.”<BR>”;
for($i=0;i<2;$i++)
6. Classes and
objects
{
7. Predefined
classes
echo $this->courses[i].‟ = „.$this->scores[i].”<BR>”;
3. PHP programming
styles
}
}
}
?>
Sevilla, noviembre de 2010
Grupo de Ingeniería del Software
21
[Ángel US V7] Diseño: Amador Durán Toro (2003-2006)
Introduction to PHP
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
1. Introduction
2. The PHP Language
1. Comments
2. Types
3. Variables
4. Functions
5. Control flow
structures
• PHP allows declaring static and constant members
using reserved words const and static.
• To access constant and state members we use
resolution operator “::”.
<?php
class Physics {
const C = 299.792.458;
6. Classes and
objects
7. Predefined
classes
3. PHP programming
styles
static GRAVITY = 9. 8;
//…
}
$aceleration=Physics:: GRAVITY;
?>
• Resolut ion operator can be used with self (to
access static member of the proper class) and
parent (to access members and methods of
parent classes).
Sevilla, noviembre de 2010
Grupo de Ingeniería del Software
22
[Ángel US V7] Diseño: Amador Durán Toro (2003-2006)
Introduction to PHP
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
• PHP incorporates a cloning method called clone
(it invokes the private method __clone() that can
be overwritten by any class)
1. Introduction
2. The PHP Language
1. Comments
2. Types
3. Variables
• PHP semantics of compare operators on objects
(PHP v.5 or higher):
4. Functions
5. Control flow
structures
6. Classes and
objects
7. Predefined
classes
3. PHP programming
styles
– $obj1 == $obj2: True if $obj1 and $obj2 are
objects with equal values for their properties
and are instances of the same class
– $obj1 === $obj2: True if $obj1 and $obj2 are
the same instance.
Sevilla, noviembre de 2010
Grupo de Ingeniería del Software
23
[Ángel US V7] Diseño: Amador Durán Toro (2003-2006)
Introduction to PHP
• PHP code modularization
– Include functions can be used to add php code to
our pages. There are four include functions:
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
1. Introduction
•
include(„/path/file‟)
1. Comments
•
include_once(„/path/file‟)
2. Types
•
require(„/path/file‟)
3. Variables
•
require_once(„/path/file‟)
2. The PHP Language
4. Functions
– Included files are treated as HTML.
6. Classes and
objects
3. PHP programming
styles
If inclusion fails, an error is generated
and processing aborts
File included once
5. Control flow
structures
7. Predefined
classes
If inclusion fails, processing continues
<html>
…
<?php
…
include($_SERVER[„DOCUMENT_ROOT‟].‟/Functions.inc‟)
;
function f()
{
…
…
?>
}
…
</html>
Sevilla, noviembre de 2010
Grupo de Ingeniería del Software
Functions.inc
24
[Ángel US V7] Diseño: Amador Durán Toro (2003-2006)
Introduction to PHP
•
Escuela Técnica Superior
de Ingeniería Informática
Departamento de Lenguajes
y Sistemas Informáticos
1. Introduction
Those functions can be used to include common
content –header, navigation, footer- to our web
site .
<? include($_SERVER[„DOCUMENT_ROOT‟].‟/Header.inc‟);? >
2. The PHP Language
1. Comments
…
2. Types
<?
3. Variables
// Code
4. Functions
?>
…
5. Control flow
structures
<? include($_SERVER[„DOCUMENT_ROOT‟].‟/Footer.inc‟);?>
6. Classes and
objects
7. Predefined
classes
3. PHP programming
styles
•
Include and Header are absolutely different
functions:
– Include/Require: content is imported on the page, but we
use the same url and there is no new request.
– Header(“Location: XXX”): Is a redirection, shows a new
url and performs a new request.
Sevilla, noviembre de 2010
Grupo de Ingeniería del Software
25
Descargar