Sie sind auf Seite 1von 95

1

http://server/path/file
 Usually when you type a URL in your
browser:
 Your computer looks up the server's IP address
using DNS
 Your browser connects to that IP address and
requests the given file
 The web server software (e.g. Apache) grabs that file
from the server's local file system
 The server sends back its contents to you

CS380 2
Apache,
Websphere
SW(Java Servlets,
XML Files)

Web/Application Server Database

3
http://www.facebook.com/home.p
hp
 Some URLs actually specify programs that the
web server should run, and then send their
output back to you as the result:
 The above URL tells the server facebook.com to run
the program home.php and send back its output

CS380 4
 Server-side pages are programs written using
one of many web programming
languages/frameworks
 examples: PHP, Java/JSP, Ruby on Rails, ASP.NET,
Python, Perl

CS380 5
 Also called server side scripting:
 Dynamically edit, change or add any content to a
Web page
 Respond to user queries or data submitted from
HTML forms
 Access any data or databases and return the results
to a browser
 Customize a Web page to make it more useful for
individual users
 Provide security since your server code cannot be
viewed from a browser

6
 Web server:
 contains software that allows it to run server side
programs
 sends back their output as responses to web requests
 Each language/framework has its pros and
cons
 we use PHP

CS380 7
 PHP stands for "PHP Hypertext Preprocessor"
 Server-side scripting language
 Used to make web pages dynamic:
 provide different content depending on context
 interface with other services: database, e-mail, etc.
 authenticate users
 process form information
 PHP code can be embedded
in XHTML code

CS380 8
Hello.php
Hello world!

User’s computer Server computer 9


 Free and open source
 Compatible
 as of November 2006, there were more than 19
million websites (domain names) using PHP.
 Simple

CS380 10
 PHP is server side scripting system
 PHP stands for "PHP: Hypertext Preprocessor"
 Syntax based on Perl, Java, and C
 Very good for creating dynamic content
 Powerful, but somewhat risky!
 If you want to focus on one system for dynamic
content, this is a good one to choose
 Started as a Perl hack in 1994 by Rasmus
Lerdorf (to handle his resume), developed to
PHP/FI 2.0
 By 1997 up to PHP 3.0 with a new parser
engine by Zeev Suraski and Andi Gutmans
 Version 5.2.4 is current version, rewritten by
Zend (www.zend.com) to include a number of
features, such as an object model
 Current is version 5
 php is one of the premier examples of what an
open source project can be
 A Commercial Enterprise
 Zend provides Zend engine for PHP for free
 They provide other products and services for a
fee
 Server side caching and other optimizations
 Encoding in Zend's intermediate format to protect
source code
 IDE-a developer's package with tools to make life
easier
 Support and training services
 Zend's web site is a great resource
 Zend engine as parser (Andi Gutmans and Zeev
Suraski)
 SAPI is a web server abstraction layer
 PHP components now self contained (ODBC, Java,
LDAP, etc.)
 This structure is a good general design for software
(compare to OSI model, and middleware applications)

image from http://www.zend.com/zend/art/in


 Typically file ends in .php--this is set by the
web server configuration
 Separated in files with the <?php ?> tag
 php commands can make up an entire file, or
can be contained in html--this is a choice….
 Program lines end in ";" or you get an error
 Server recognizes embedded script and
executes
 Result is passed to browser, source isn't visible
<P>
<?php $myvar = "Hello World!";
echo $myvar;
?>
</P>
 We've talk about how the browser can read a
text file and process it, that's a basic parsing
method
 Parsing involves acting on relevant portions of
a file and ignoring others
 Browsers parse web pages as they load
 Web servers with server side technologies like
php parse web pages as they are being passed
out to the browser
 Parsing does represent work, so there is a cost
 You can embed sections of php inside html:
<BODY>
<P>
<?php $myvar = "Hello World!";
echo $myvar;
</BODY>

 Or you can call html from php:

<?php
echo "<html><head><title>Howdy</title>

?>
<?php
print "Hello, world!";
?> PHP

Hello world!
output

CS380 18
Hello world!

19
HTML content
<?php
PHP code
?>
HTML content
<?php
PHP code
?>
HTML content ... PHP

 Contents of a .php file between <?php and ?> are executed as PHP code
 All other contents are output as pure HTML
 We can switch back and forth between HTML and PHP "modes"

20
print "text";
PHP

print "Hello, World!\n";


print "Escape \"chars\" are the SAME as in Java!\n";
print "You can have
line breaks in a string.";
print 'A string can use "single-quotes". It\'s cool!';
PHP

Hello world! Escape "chars" are the SAME as in Java! You can have line
breaks in a string. A string can use "single-quotes". It's cool!
output

CS380 21
$name = expression; PHP

$user_name = “mundruid78";
$age = 16;
$drinking_age = $age + 5;
$this_class_rocks = TRUE; PHP

 names are case sensitive


 names always begin with $, on both
declaration and usage
 always implicitly declared by assignment
(type is not written)
 a loosely typed language (like JavaScript or
Python) 22
 basic types: int, float, boolean, string, array,
object, NULL
 test type of variable with is_type functions, e.g.
is_string
 gettype function returns a variable's type as a
string
 PHP converts between types automatically in
many cases:
 string→ int auto-conversion on +
 int → float auto-conversion on /

 type-cast with (type):


 $age = (int) "21"; 23
 Typed by context (but one can force type), so it's
loose
 Begin with "$" (unlike javascript!)
 Assigned by value
 $foo = "Bob"; $bar = $foo;
 Assigned by reference, this links vars
 $bar = &$foo;
 Some are preassigned, server and env vars
 For example, there are PHP vars, eg. PHP_SELF,
HTTP_GET_VARS

00
 The phpinfo() function shows the php
environment
 Use this to read system and server variables,
setting stored in php.ini, versions, and modules
 Notice that many of these data are in arrays
 This is the first script you should write…

00_phpinfo.php
 Using the value of a variable as the name of a
second variable)
$a = "hello";
$$a = "world";
 Thus:
echo "$a ${$a}";
 Is the same as:
echo "$a $hello";

 But $$a echoes as "$hello"….

00_hello_world.php
 + - * / % . ++ --
 = += -= *= /= %= .=
 many operators auto-convert types: 5 + "7" is
12

CS380 27
# single-line comment
// single-line comment
/*
multi-line comment
*/ PHP

 like Java, but # is also allowed


a lot of PHP code uses # comments instead of //

CS380 28
$favorite_food = "Ethiopian";
print $favorite_food[2];
$favorite_food = $favorite_food . " cuisine";
print $favorite_food;
PHP

 zero-based indexing using bracket notation


 there is no char type; each letter is itself a String
 string concatenation operator is . (period), not +
 5 + "2 turtle doves" === 7
 5 . "2 turtle doves" === "52 turtle doves"
 can be specified with "" or ''

CS380 29
# index 0123456789012345
$name = "Stefanie Hatcher";
$length = strlen($name);
$cmp = strcmp($name, "Brian Le");
$index = strpos($name, "e");
$first = substr($name, 9, 5);
$name = strtoupper($name);
PHP

CS380 30
Name Java Equivalent
strlen length
strpos indexOf
substr substring
strtolower, strtoupper toLowerCase, toUpperCase
trim trim
explode, implode split, join
strcmp compareTo

CS380
31
$age = 16;
print "You are " . $age . " years old.\n";
print "You are $age years old.\n"; # You are 16 years old.
PHP

 strings inside " " are interpreted


 variables that appear inside them will have their
values inserted into the string
 strings inside ' ' are not interpreted:
print ' You are $age years old.\n '; # You are $age years
old. \n PHP

CS380 32
print "Today is your $ageth birthday.\n"; # $ageth not
found
print "Today is your {$age}th birthday.\n";
PHP

 if necessary to avoid ambiguity, can enclose


variable in {}

CS380 33
$name = “Xenia";
$name = NULL;
if (isset($name)) {
print "This line isn't going to be reached.\n";
} PHP

 a variable is NULL if
 it has not been set to any value (undefined variables)

 it has been assigned the constant NULL

 it has been deleted using the unset function

 can test if a variable is NULL using the isset function


 NULL prints as an empty string (no output)

CS380 34
Defined: A method of specifying a search string
using a number of special characters that can
precisely match a substring.

Purpose: Regular expressions allow you to


perform complex pattern matching on strings. A
small regular expression can replace the need
for a large amount of code

Example for e-mail validation:


^[A-Za-z0-9._%-]+@[A-Za-z0-9._%-]+\.[A-Za-z]{2,4}$
35
Description: Quantifiers are wildcards that specify how
many times to match the preceding string pattern.
Alternate
Quantifier Meaning
Notation

* Match zero or more of previous {0,}

+ Match one or more of previous {1,}

? Match one or zero of previous {0,1}

{num} Match exactly num of previous

{min,} Match at least min of previous

{min,max} Match at least min but not more than max


of previous characters

36
Description: Anchors define a specific location for the
match to take place.

Anchor Meaning
^ Match start of line
$ Match end of line
. Match any single character
\b Match word boundary
\B Match non-word boundary

37
Defined: A method of matching a set of characters.

Examples
Match any upper or lower case alpha character:
[A-Za-z]

Match any lower case vowel character:


[aeiou]

Match any numeric digit character:


[0-9]
38
Defined: A method of matching characters that are outside the specified
set.

Examples
Match any non-alpha character:
[^A-Za-z]

Match any non-vowel character:


[^aeiou]

Match any non-numeric digit:


[^0-9]

Match any character outside the ASCII range (e.g. non-printable


characters like tab, linefeed, CTRL, etc.):
[^ -~]
39
Defined: The vertical pipe character allows you to
match one string or another.

Example:
Match the string “red”, “white”, or “blue”:

Regular Expression:
red|white|blue

40
Defined: Parentheses can be used to group
regular expressions.

Example:
Match any of the following:
a long time ago
a long long time ago
a long long long time ago

Regular Expression:
(long )+
41
Greedy Defined: By default, regular expressions are
“greedy” meaning that '.*' and '.+' will always
match as the longest string.

Example:
Given the string:
do <b>not</b> press

And the regular expression:


<.*>

The resulting match would be:


<b>not</b>
42
 Non-greedy Defined: Non-greedy quantifiers specify
minimal string matching. A question mark “?” placed
after the wildcard, cancels the “greedy” regular
expression behavior.

Example:
Given the string:
do <b>not</b> press

And the regular expression:


<.*?>

The resulting match would be:


<b>
43
Defined: A method of matching a set of characters.

Symbol Meaning Alternate Notation

\s Match whitespace [\r\n \t]


\S Match non-whitespace [^\r\n \t]
\w Match word character [A-Za-z0-9_]
\W Match non-word character [^A-Za-z0-9_]
\d Match a numeric digit [0-9]
\D Match a non-numeric digit [^0-9]

44
Description: Modifiers change the matching
behavior of the regular expression.
Modifier Meaning
i Ignore case (case insensitive)
s Dot matches all characters
m Match start and end of line
anchors at embedded new lines
in search string
Example match upper and lower case “abc”:
'/abc/i'
45
Discussion: PHP functions that use Perl
regular expressions start with
“preg_”. The regular expressions are
in Perl format meaning, they start and
end with a slash. In order to prevent
variable expansion, regular
expressions are usually specified with
single quotes.
46
Discussion: The function “preg_match()” returns the number of times a
pattern matches a string. Because it returns zero if there are no matches,
this function works ideal in an “if” statement.

Example:
<?php
$subject = "Jack and Jill went up the hill.";
$pattern = '/jack|jill/i';

if ( preg_match( $pattern, $subject ) )


{
printf( "Regular expression matched." );
}
?>
47
 int preg_match ( string $pattern , string $subjec
t [, array &$matches [, int$flags =
0 [, int $offset = 0 ]]] )
 PREG_OFFSET_CAPTUREIf this flag is
passed, for every occurring match the
appendant string offset will also be returned
Discussion: The function “preg_match_all()” returns the number of times a pattern
matches a string. Because it returns zero if there are no matches, this function
works ideal in an “if” statement.

Example:
<?php
$subject = "Every good boy deserves fudge.";
$pattern = '/[aeiou]/i';

preg_match_all( $pattern, $subject, $matches );

$total = count( $matches[0] ); // matches array

printf( "String contains %d vowels",


$total );
?> 49
 <?php
preg_match_all("|<[^>]+>(.*)</[^>]+>|U",
"<b>example: </b><div align=left>this is a test</div>",
$out, PREG_PATTERN_ORDER);
echo $out[0][0] . ", " . $out[0][1] . "\n";
echo $out[1][0] . ", " . $out[1][1] . "\n";
?>
 PREG_PATTERN_ORDER-Orders results so
that $matches[0] is an array of full pattern
matches, $matches[1] is an array of strings
matched by the first parenthesized subpattern, and
so on.
 PREG_SET_ORDER-Orders results so
that $matches[0] is an array of first set of
matches, $matches[1] is an array of second set of
matches, and so on.
 PREG_OFFSET_CAPTURE-If this flag is passed,
for every occurring match the appendant string
offset will also be returned
 preg_filter ( $pattern , $replacement , $subject
[, int $limit = -1 [, int &$count ]] )
 <?php
$subject = array('1', 'a', '2', 'b', '3', 'A', 'B', '4');
$pattern = array('/\d/', '/[a-z]/', '/[1a]/');
$replace = array('A:$0', 'B:$0', 'C:$0');
echo "preg_filter returns\n";
print_r(preg_filter($pattern, $replace, $subject));
echo "preg_replace returns\n";
print_r(preg_replace($pattern, $replace, $subject));
?>
 array preg_grep ( string $pattern , array $input
[, int $flags = 0 ] )
 flagsIf set to PREG_GREP_INVERT, this
function returns the elements of the input array
that do not match the given pattern.
 <?php
// return all array elements
// containing floating point numbers
$fl_array = preg_grep("/^(\d+)?\.\d+$/", $arr
ay);
?>
 preg_last_error — Returns the error code of the last PCRE regex execution
 int preg_last_error ( void )
 <?php
preg_match('/(?:\D+|<\d+>)*[!?]/', 'foobar foobar foobar');
if (preg_last_error() == PREG_BACKTRACK_LIMIT_ERROR) {
print 'Backtrack limit was exhausted!';
}
?>
 PREG_NO_ERROR
 PREG_INTERNAL_ERROR
 PREG_BACKTRACK_LIMIT_ERROR (see also pcre.backtrack_limit)
 PREG_RECURSION_LIMIT_ERROR (see also pcre.recursion_limit)
 PREG_BAD_UTF8_ERROR
 PREG_BAD_UTF8_OFFSET_ERROR (since PHP 5.3.0)
 PREG_JIT_STACKLIMIT_ERROR (since PHP 7.0.0)
 string preg_quote ( string $str [, string $delimit
er = NULL ] )
 <?php
$keywords = '$40 for a g3/400';
$keywords = preg_quote($keywords, '/');
echo $keywords; // returns \$40 for a g3\/400
?>
 preg_replace — Perform a regular expression
search and replace
 preg_replace( $pattern , $replacement , $subject
[, int$limit = -1 [, int &$count ]] )
 <?php
$string = 'April 15, 2003';
$pattern = '/(\w+) (\d+), (\d+)/i';
$replacement = '${1}1,$3';
echo preg_replace($pattern, $replacement, $stri
ng);
?>
 Ereg()-searches a pattern specified by a string
 Ereg_replace()-search and replace a string or a
pattern
 Eregi()-search for a string or a pattern case
insensitive
 Split()-divide a string into various elements
 preg_split — Split string by a regular expression
 array preg_split ( string $pattern , string $subject [, int
$limit = -1 [, int$flags = 0 ]] )
 PREG_SPLIT_NO_EMPTY-If this flag is set, only non-
empty pieces will be returned by preg_split()
 PREG_SPLIT_DELIM_CAPTURE-If this flag is set,
parenthesized expression in the delimiter pattern will
be captured and returned as well.
 PREG_SPLIT_OFFSET_CAPTURE-If this flag is set,
for every occurring match the appendant string offset
will also be returned. Note that this changes the return
value in an array where every element is an array
consisting of the matched string at offset 0 and its
string offset into subject at offset 1.
 <?php
// split the phrase by any number of commas
or space characters, which include " ", \r, \t, \n
and \f
$keywords = preg_split("/[\s,]+/", "hypertext l
anguage, programming");
print_r($keywords);
?>
 Wide Variety available
 if, else, elseif
 while, do-while
 for, foreach
 break, continue, switch
 require, include, require_once, include_once
 Mostly parallel to what we've covered already
in javascript
 if, elseif, else, while, for, foreach, break and
continue
 Switch, which we've seen, is very useful
 These two do the same
things…. switch ($i) {
case 0:
echo "i equals 0";
break;
if ($i == 0) { case 1:
echo "i equals 0"; echo "i equals 1";
} elseif ($i == 1) { break;
echo "i equals 1"; case 2:
} elseif ($i == 2) { echo "i equals 2";
echo "i equals 2"; break;
} }
for (initialization; condition; update) {
statements;
}
PHP

for ($i = 0; $i < 10; $i++) {


print "$i squared is " . $i * $i . ".\n";
}
PHP

CS380 63
$feels_like_summer = FALSE;
$php_is_great = TRUE;
$student_count = 7;
$nonzero = (bool) $student_count; # TRUE
PHP
 the following values are considered to be
FALSE (all others are TRUE):
0 and 0.0 (but NOT 0.00 or 0.000)
 "", "0", and NULL (includes unset variables)

 arrays with 0 elements

 FALSE prints as an empty string (no output);


TRUE prints as a 1
CS380 64
if (condition) {
statements;
} elseif (condition) {
statements;
} else {
statements;
}
PHP

CS380 65
while (condition) {
statements;
} PHP

do {
statements;
} while (condition);
PHP

CS380 66
$a = 3;
$b = 4;
$c = sqrt(pow($a, 2) + pow($b, 2));
PHP

math functions

abs ceil cos floor log log10 max


min pow rand round sin sqrt tan
math constants
M_PI M_E M_LN2

CS380 67
$a = 7 / 2; # float: 3.5
$b = (int) $a; # int: 3
$c = round($a); # float: 4.0
$d = "123"; # string: "123"
$e = (int) $d; # int: 123 PHP

 int for integers and float for reals


 division between two int values can produce a float

CS380 68
$name = array(); # create
$name = array(value0, value1, ..., valueN);
$name[index] # get element value
$name[index] = value; # set element value
$name[] = value; # append PHP

$a = array(); # empty array (length 0)


$a[0] = 23; # stores 23 at index 0 (length 1)
$a2 = array("some", "strings", "in", "an", "array");
$a2[] = "Ooh!"; # add string to end (at index 5)
PHP

 Append: use bracket notation without specifying an index


 Element type is not specified; can mix types

CS380 69
function name(s) description
count number of elements in the array
print_r print array's contents
array_pop, array_push,
using array as a stack/queue
array_shift, array_unshift
in_array, array_search, array_reverse,
searching and reordering
sort, rsort, shuffle
array_fill, array_merge,
array_intersect, creating, filling, filtering
array_diff, array_slice, range
array_sum, array_product,
array_unique, processing elements
array_filter, array_reduce

70
$tas = array("MD", "BH", "KK", "HM", "JP");
for ($i = 0; $i < count($tas); $i++) {
$tas[$i] = strtolower($tas[$i]);
}
$morgan = array_shift($tas);
array_pop($tas);
array_push($tas, "ms");
array_reverse($tas);
sort($tas);
$best = array_slice($tas, 1, 2);
PHP

 the array in PHP replaces many other collections in Java


 list, stack, queue, set, map, ...

CS380 71
foreach ($array as $variableName) {
...
} PHP

$fellowship = array(“Frodo", “Sam", “Gandalf",


“Strider", “Gimli", “Legolas", “Boromir");
print “The fellowship of the ring members are: \n";
for ($i = 0; $i < count($fellowship); $i++) {
print "{$fellowship[$i]}\n";
}
print “The fellowship of the ring members are: \n";

foreach ($fellowship as $fellow) {


print "$fellow\n";
} PHP

CS380 72
<?php $AmazonProducts = array( array(“BOOK",
"Books", 50),
array("DVDs",
“Movies", 15),
array(“CDs", “Music",
20)
);
for ($row = 0; $row < 3; $row++) {
for ($column = 0; $column < 3; $column++) { ?>
<p> | <?=
$AmazonProducts[$row][$column] ?>
<?php } ?>
</p>
<?php } ?>
PHP

CS380 73
<?php $AmazonProducts = array( array(“Code” =>“BOOK",
“Description” => "Books", “Price” => 50),
array(“Code” => "DVDs",
“Description” => “Movies", “Price” => 15),
array(“Code” => “CDs",
“Description” => “Music", “Price” => 20)
);
for ($row = 0; $row < 3; $row++) { ?>
<p> | <?= $AmazonProducts[$row][“Code”] ?> | <?=
$AmazonProducts[$row][“Description”] ?> | <?=
$AmazonProducts[$row][“Price”] ?>
</p>
<?php } ?>
PHP

CS380 74
 You can directly read data into individual
array slots via a direct assignment:
$pieces[5] = "poulet resistance";
 From a file:
 Use the file command to read a delimited file (the
delimiter can be any unique char):
$pizza = file(./our_pizzas.txt)
 Use explode to create an array from a line within a
loop:
$pieces = explode(" ", $pizza);
 The power of php lies partially in the wealth of
functions---for example, the 40+ array
functions
 array_flip() swaps keys for values
 array_count_values() returns an associative array of
all values in an array, and their frequency
 array_rand() pulls a random element
 array_unique() removes duppies
 array_walk() applies a user defined function to each
element of an array (so you can dice all of a dataset)
 count() returns the number of elements in an array
 array_search() returns the key for the first match in
an array

08_array_fu.php
 Like javascript, php supports user defined
functions
 Declare your functions towards the top of your
php file--this is not a requirement, just good
practice
 Functions are created when the program is
read, and before execution
 Or, build an exterior file with commonly used
functions, and give that a version number.
Then require that file to reuse your code (see
the general functions file in the samples for
examples I use)
 The simplest way to pass data into a
function is through that functions argument
list of variable (and arrays are a type of
variable)
// wrap the variable in p
function echo_p($wrapped_item) {
echo "<p>$wrapped_item</p>";
}
 You can also set default values, but watch
placement--defaults to the right please
// wrap the variable in h
// default to level 2
function echo_h($wrapped_item, $level="2") {
echo "<h" . $level . ">$wrapped_item</h" . $level. ">\n";
}

12
 Functions themselves have global scope--
functions defined within functions are
available everywhere
 Variables assigned or modified inside of a
function have their value only within the
function
 A variable can be declared global within a
function, however, if you want to pass that
variable into and out of the function
 Generally, it's better to leave variable scope
limited, this makes the function portable….
15
function foo() {
 Unlike variables, function bar() {
functions are echo "I don't exist until foo() is called.\n";
global in scope }
}

 But a function
doesn't execute /* We can't call bar() yes since it doesn't exist.
*/
until called
 Here, foo() is used foo();
to create bar() /* Now we can call bar(), foo()'s processing has
 Once foo() is made it accessible. */
called, bar() exists bar();

 bar() is available ?>


outside of foo()
function good_echo_h($wrapped_item, $level="2")  Defaults
{
echo "<h" . $level . ">$wrapped_item</h" . $level. ">\n"; must occur
} to the right
function bad_echo_h($level="2", $wrapped_item)
{
echo "<h" . $level . ">$wrapped_item</h" . $level. ">\n";
}

good_echo_h("A good heading");


good_echo_h("A good heading at level 1", 1);
bad_echo_h(2, "A bad heading with level set");
bad_echo_h("A bad heading with no level set");
 We use the function keyword to define a
function, we name the function and take
optional argument variables. The body of the
function is in a block of code { }

function greet() {
print "Hello\n";
} Hello
Hello
greet(); Hello
greet();
greet();
 Often a function will take its arguments, do some
computation and return a value to be used as the
value of the function call in the calling
expression. The return keyword is used for this.

function greeting() {
return "Hello"; Hello Glenn
} Hello Sally

print greeting() . " Glenn\n";


print greeting() . " Sally\n";
 Functions can choose to accept optional
arguments. Within the function definition the
variable names are effectively "aliases" to the
values passed in when the function is called.

function howdy($lang) {
if ( $lang == 'es' ) return "Hola";
if ( $lang == 'fr' ) return "Bonjour";
return "Hello"; Hola Glenn
Bonjour Sally
}

print howdy('es') . " Glenn\n";


print howdy('fr') . " Sally\n";
 Arguments can have defaults and so can be
omitted
function howdy($lang='es') {
if ( $lang == 'es' ) return "Hola";
if ( $lang == 'fr' ) return
"Bonjour";
return "Hello"; Hola Glenn
} Bonjour Sally

print howdy() . " Glenn\n";


print howdy('fr') . " Sally\n";
 Much like variable names - but do not start with
a dollar sign
 Start with a letter or underscore - consist of letters,
numbers, and underscores ( _ )
 Avoid built in function names
 The argument variable within the function is
an "alias" to the actual variable
 But even further, the alias is to a *copy* of the
actual variable in the function call

function double($alias) {
$alias = $alias * 2;
return $alias; Value = 10 Doubled = 20
}
$val = 10;
$dval = double($val);
echo "Value = $val Doubled = $dval\n";
 Sometimes we want a function to change one
of its arguments - so we indicate that an
argument is "by reference" using ( & )

function triple(&$realthing) {
$realthing = $realthing * 3;
}

$val = 10;
triple($val);
echo "Triple = $val\n"; Triple = 30
 In general, variable names used inside of function
code, do not mix with the variables outside of the
function. They are walled-off from the rest of the
code. This is done because you want to avoid
"unexpected" side effects if two programmers use
the same variable name in different parts of the
code.
 We call this "name spacing" the variables. The
function variables are in one "name space" whilst
the main variables are in another "name space"
 Like little padded cells of names - like silos to keep
things spearate
function tryzap() {
$val = 100;
}
TryZap = 10
$val = 10;
tryzap();
echo "TryZap = $val\n";
function dozap() {
global $val;
$val = 100;
}
DoZap = 100

$val = 10;
dozap();
echo "DoZap = $val\n";

Use this wisely, young Jed


 Passing variable in as parameter
 Passing value back as return value
 Passing variable in by reference
 If you use Global Variables use really long
names with nice unique prefixes
• 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 the static keyword when you first


declare the variable:
 <?php
function myTest()
{
static $x=0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
• Then, each time the function is called, that
variable will still have the information it
contained from the last time the function was
called.

• Note: The variable is still local to the function.

Das könnte Ihnen auch gefallen