php basics 1 ics213, 1 / 2011 dr. seung hwan kang 1
TRANSCRIPT
PHP Basics 1
ICS213, 1 / 2011Dr. Seung Hwan Kang
1
Outline•I
ntroduction to PHP•C
omments•V
ariables•T
ype•T
ype Casting•C
onstants•O
perators•C
ontrol Structures•M
isc. Functions
2
What is PHP?•P
HP, which stands for "PHP: Hypertext Preprocessor" is a widely-used Open Source general-purpose scripting language that is especially suited for Web development and can be embedded into HTML. Its syntax draws upon C, Java, and Perl, and is easy to learn. The main goal of the language is to allow web developers to write dynamically generated web pages quickly, but you can do much more with PHP.
3
•There are three main areas where PHP scripts are used. • Server-side scripting.• Command line scripting.• Writing desktop applications.
•The following databases are currently supported: • IBM DB2, Informix, MySQL, ODBC, Oracle, PostgresSQL, SQLite, Sybase, etc.,
• PHP Data Objects (PDO)
•LDAP, IMAP, SNMP, NNTP, POP3, HTTP, COM, SAX, XML, XSLT, etc.,
4
What can PHP do?
Getting Started•P
HP is installed on the Apache HTTP Server (httpd)•A
ll files ending in .php are handled by PHP.• e.g. index.php, helloworld.php
•Server parses files based on extensions
•Returns plain HTML, no code
•Think of these PHP-enabled files as simple HTML files with a whole new family of magical tags that let you do all sorts of things.
5
•Open and close tags: <?php ?>
<?php
echo "Hello World!";
?>
6
Hello World
Hello World (cont’d)<!
DOCTYPE HTML><html>
<head>
<title>Example</title>
</head>
<body>
<?php
echo "Hello World!";
?>
</body>
</html>
7helloworld.php
<?php//
$expression = TRUE;if
($expression) { ?>
<h1>This is true.</h1> <?
php} else { ?>
<h1>This is false.</h1> <?
php}?>
8escape.php
Escaping from HTML
Comment
<?php
// one-line comment
/*
* multi line comment
*/
echo "Hello World!";
?>
9
In PHP, you create a variable with a dollar sign ($) and some text.
Usually the text will be something descriptive of what it is going to hold.
<?php
$name = "Web Programming";
$code = 'ICS213';
$credit = 3;
$semester = "1 / 2011";
?>
10
Variable
•Output one or more strings
<?php
echo ("Hello World");
echo "Hello World";
echo "This spans\nmultiple lines. The newlines will be\noutput as well.";
echo "Escaping characters is done \"Like this\".";
?>
11
Echo, Print
Echo, Print (cont’d)<?php
$foo = "foobar";$bar = "barbaz";
echo "foo is $foo"; // foo is foobar
echo 'foo is $foo'; // foo is $foo
echo $foo; // foobarecho $foo,$bar; // foobarbarbaz
echo "foo is " . $foo; // foo is foobar
// preferred
?>
12echo.php
13
Reserved Word
•Booleans
•Integers
•Floating point numbers
•Strings
•Arrays
•Objects
•Resources
•NULL
14
Types
It can be either TRUE or FALSE
<?php
$foo = TRUE;
?>
15booleans.php
Boolean
An integer is a number of the set Z = {..., -2, -1, 0, 1, 2, ...}
<?php$int1
= 1234; // decimal number$int2
= -123; // a negative number$int3
= 0123; // octal number$int4
= 0x1A; // hexadecimal number?>
16
Integer
also known as "floats", "doubles", or "real numbers"
<?php$num1 = 1.234; $num2 = 1.2e3; $num3 = 7e-10;?>
17
Float pointing numbers
floats.php
A string is series of characters
<?phpecho 'this is a simple string';
// Outputs: "I'll be back"echo '"I\'ll be back"';
// Outputs: Variables do not $expand $eitherecho 'Variables do not $expand $either';?>
18
String
.•S
tring catenation is indicated with a period (.)
<?php
$str1 = 'Hello';
// Outputs: Hello World PHP!
echo "$str1 World" . " PHP!";
?>
19string.php
Simple array
<?php
$arr = array(1,2,3,4,5);
echo $arr[3];
?>
20
// 4
array1.php
Array
Array (cont’d)a
rray( key => value , ... ) // key may
only be an integer or string // value may
be any value of any type
<?php
$arr = array('foo' => 'bar', 12 => true);
echo $arr['foo']; // bar
echo $arr[12]; // 1
?>21array2.php
Array (cont’d)<
?php
// This array is the same as ...
$arr1 = array(5 => 43, 32, 56, 'b' => 12);
// ...this array
$arr2 = array(5 => 43, 6 => 32, 7 => 56, 'b' => 12);
?>
22array3.php
To create a new object , use the new statement to instantiate a class:
<?phpclass Robot { public $name; public function
setName($name) { $this->name =
$name; } public function
getName() { return $this-
>name; } public function
__toString() { return $this-
>name; }}
$bender1 = new Robot();
$bender1->setName("Bender 1");
echo $bender1->__toString();
?>
23object.php
Object
•The special NULL value represents a variable with no value.
<?php
$var = NULL; ?
>
24
null.php
NULL
•(int), (integer) - cast to integer
•(bool), (boolean) - cast to boolean
•(float), (double), (real) - cast to float
•(string) - cast to string
•(binary) - cast to binary string (PHP 6)
•(array) - cast to array
•(object) - cast to object
•(unset) - cast to NULL (PHP 5)
25
Type Casting
Type Casting<?
php$f
oo = 10; // $foo is an integer$s
tr = "$foo"; // $str is a string$f
st = (string) $foo; // $fst is also a string
// This prints out that "they are the same"
if ($fst === $str) {
echo "they are the same";
}?>
26casting.php
ConstantA
constant is case-sensitive by default
<?php
// a valid constant name
define('HOST', 'localhost');
echo HOST; // localhost
?>
27config.php
•Arithmetic Operators
•Assignment Operator
•Comparison Operators
•Incrementing/Decrementing Operators
•Logical Operators
•String Operators
•Type Operators
28
Operators
•PHP supports the usual operators supported by the C/C++/Java family
29
Arithmetic Operators
•The assignment operator (=) used in C/C++/Java are supported in PHP
<?php$a = ($b = 4) + 5; ?>
30
Assignment Operator
Example
Name
Result
$a == $b
Equal
TRUE if $a is equal to $b.
$a === $b
Identical
TRUE if $a is equal to $b, and they are of the same type. (introduced in PHP 4)
$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. (introduced in PHP 4)
$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.
31
Comparison Operators
Incrementing/Decrementing Operators
Example
Name
Effect
++$a
Pre-increment
Increments $a by one, then returns $a.
$a++
Post-increment
Returns $a, then increments $a by one.
--$a
Pre-decrement
Decrements $a by one, then returns $a.
$a--
Post-decrement
Returns $a, then decrements $a by one.
32
Example
Name
Result
$a and $b
And
TRUE if both $a and $b are TRUE.
$a or $b
Or
TRUE if either $a or $b is TRUE.
$a xor $b
Xor
TRUE if either $a or $b is TRUE, but not both.
! $a
Not
TRUE if $a is not TRUE.
$a && $b
And
TRUE if both $a and $b are TRUE.
$a || $b
Or
TRUE if either $a or $b is TRUE.
33
Logical Operators
Example
Name
Result
$a = "Hello ";$b = $a . "World!";
concatenation operator
“Hello World!”
$a = "Hello ";$a .= "World!";
concatenating assignment operator
“Hello World!”
34
String Operators
Type Operators•i
nstanceof is used to determine whether a PHP variable is an instantiated object of a certain class:
<?phpclass
ParentClass {}
class MyClass extends ParentClass {
}
$a = new MyClass;
var_dump($a instanceof MyClass); // bool (true)
var_dump($a instanceof ParentClass); // bool (true)
?>
35type_op.php
•If, else, else if
•while
•do-while
•for
•foreach
•break
•continue
•switch
•require
•include
36
Control Structures
<?php$a = 8;
$b = 8;
if ($a > $b) { echo "a is bigger than b";} else { echo "a is NOT bigger than b";}?>
37
if
while (expr)
statement
<?php$i = 1
;while
($i < 10){
echo $i++; }?>
38while.php
while
while loops is guaranteed to run the first iteration of a do-while loop
<?php$i =
0;do {
echo $i;}
while ($i > 0);?>
39
dowhile.php
do-while
for (expr1; expr2; expr3)
statement
<?php
for ($i = 1; $i <= 10; $i++) {
echo $i;
}?>
40
for.php
for
foreachf
oreach (array_expression as $value)
statement
•it loops over the array given by array_expression. On each loop, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next loop, you'll be looking at the next element)
foreach (array_expression as $key => $value)
statement
•The second form does the same thing, except that the current element's key will be assigned to the variable $key on each loop.
41
foreach (cont’d)f
oreach (array_expression as $value)
statement
<?php$arr =
array('one', 'two', 'three');
foreach ($arr as $value) {
echo "Value: $value<br />\n";
}?>
42foreach1.php
foreach (cont’d)f
oreach (array_expression as $key => $value)
statement
<?php$arr =
array('one', 'two', 'three');
foreach ($arr as $key => $value) {
echo "Value: $value<br />\n";
}?>
43foreach2.php
break ends execution of the current for, foreach, while, do-while or switch structure.
<?php$arr =
array('one', 'two', 'stop', 'three');while
(list(, $val) = each($arr)) { if
($val == 'stop') {
break; }
echo "$val<br />\n";}?>
44break1.php
break
break (cont’d)<?php$i = 0;while (++$i) { switch ($i)
{ case 5: echo
"At 5<br />\n"; break
1; // Exit only the switch. case 10: echo
"At 10; quitting<br />\n"; break
2; // Exit the switch and //
the while. default: break; }}?>
45break2.php
continue <?php/* The
continue keyword can skip division by zero: */$i = 5;while
($i > -2){
$i--; if
($i == 0) {
continue; }
echo $i . "<br />";}?>
46continue.php
switch<?php
$i = 'orange';
switch ($i) {
case 'apple':
echo "i is apple";
break;
case 'orange':
echo "i is orange";
break;
case 'cake':
echo "i is cake";
break;
}
?>
47switch.php
include() statement includes and evaluates the specified file. When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward
include_once()
// hi.php
<?phpecho
"Hi, I'm a PHP script!";?>
// world.php
<?phpinclude
'hi.php';?>
48hi.php, world.php
include
•require() is identical to include() except upon failure it will also produce a fatal E_ERROR level error. In other words, it will halt the script whereas include() only emits a warning (E_WARNING) which allows the script to continue.
•require_once()
49hi.php, world2.php
require
HTML 5 & CSS 3
50
template.php
nav.php
section.php
footer.php
header.php
article.php
<?php// template.phpinclude_once 'header.php';…include_once 'footer.php';?>
Misc. Functionsconstant Returns the value of a constant
define Defines a named constant. See Constant
die Equivalent to exit()
exit Output a message and terminate the current script
highlight_file Syntax highlighting of a file
highlight_string Syntax highlighting of a string
51config,php, highlight_string.php
Try config.phps
Reference•P
HP Manual, http://www.php.net/manual/en/index.php