Intermediate PHP (2)File Input/Output & User Defined Functions
last week …• PHP origins & use• Basic Web 1.0 2-tier/3-tier architecture with PHP• PHP as a scripting language (supporting procedural &
oo paradigms)• Basic structure & use (statements, variables, control
structures, operators)• PHP data types - 5 basic – integer, floating-point,
string, boolean & NULL & 3 complex - array, hash & object
• PHP Functions Library (700+) – string handling, input/output, date & time, db interaction, xml processing etc. etc.
• the exit & die() statements
File Input / Output & Disk Access (1)• Reading and Writing to Files
Communicating with files follows the pattern of opening a stream to a file, reading from or writing to it, and then closing the stream.
fopen(..): the fopen function opens a file for reading or writing. The function expects the name of a file and a mode e.g.
fopen (‘c:/temp/myfile.txt’, ‘r’);
which opens a file called ‘myfile.txt’ in the directory ‘c:/temp’ in the “read” mode
File read/write modes :r reading onlyw write only, create if necessary, discard previous contenta append to file, create if necessary, start writing at endr+ reading and writingw+ reading & writing, create if necessary, discard previous contenta+ reading & writing, create if necessary, start writing at end
Input / Output & Disk Access (2)fclose (resource file) : used to close a file.feof (resource file) : as a file is read, php keeps a pointer to the
last place in the file read; the feof function returns true if the end of file is reached.
fgetcsv(resource file, integer length, string separator) : used for reading comma-separated data from a file. The optional separator argument specifies the character to separate fileds. If left out, a comma is used.
fgets(resource file, integer length) : returns a string that reads from a file. It will attempt to read as many characters – 1 as specified by the length value. A line-break character is treated as a stopping point, as is the end of the file.
fwrite(resource file, string data, integer length) : writes a string to a file. The length argument is optional and sets the number of bytes to write.
User Defined Functions (1)Functions are re-usable blocks of code that can referenced over and over again. Arguments can be passed to functions and values can be returned by them. -arguments & return values can be passed by value or reference -PHP can create functions dynamically at run-time (Lambda –Style)-References to functions can be held in variables (or arrays) - allowing functions to be a passed as arguments to other functions
- Declaring a function - functions are declared using the function statement, a name and parenthesis () e.g. function my_function() {…..}
- functions can accept any number of arguments and these are separated by commas inside the parenthesis e.g. function my_function($arg1, $arg2) {…..}
• the following simple function prints out any text passed to it as bold
<?php
function print_bold($text){print("<b>$text</b>");
}
print("This Line is not Bold<br>\n");print_bold("This Line is Bold");print("<br>\n");print("This Line is not Bold<br>\n");
?>
User Defined Functions (2)
run code
• Calculator example (from last weeks workshop)<?phpfunction calculate($x, $y, $op) {
switch($op) {case '+':
$prod = $x + $y;break;
case '-':$prod = $x - $y;break;
case '*':$prod = $x * $y;break;
case '/':$prod = $x / $y;break;
}return $prod;
}$x = 33; $y = 77; $op = '*';$prod = calculate($x, $y, $op);echo "$x $op $y = $prod";?>
User Defined Functions (3)
run code
- the return statement - at some point the function will finish and is ready to return control to the
caller - execution then picks up directly after the point the function was called - it is possible to have multiple return points from a function (but this will
reduce code readability) - if a return statement includes an expression, return(expression),
the value of the expression will be passed back - see calculator example on previous page & below <?php
function makeBold($text){$text = "<b>$text</b>";return($text);
}print("This Line is not Bold<br>\n");print(makeBold("This Line is Bold") . "<br>\n");print("This Line is not Bold<br>\n");
?>
User Defined Functions (4)
- values and references- for most data types, return values are passed by value- for objects, discussed next week, return values are returned by reference- the following function creates a new array of 10 random numbers between 1 and 100 and passes it back as a reference
<?php
function &get_rand_array() {$a = array();
for($i=0; $i<10; $i++) {$a[] = rand(1,100);
}
return($a);}
$my_new_array = &get_rand_array();print_r($my_new_array);
?>
User Defined Functions (5)
run code
User Defined Functions (6)- scope - scoping is way of avoiding name clashes between variables in
different functions - each code block belongs to a certain scope - variables within functions have local scope and are private to the
function - variables outside a function have a global scope
<?php $a = 1; // global scope function test(){ echo $a; // reference to local scope variable } test();?>The above example will output nothing because the $a inside the
function has local scope
- the global keyword can be used to access variables from the global scope within functions
<?php $a = 1; $b = 2; function sum(){ global $a, $b; $b = $a + $b; } sum(); echo $b;?>
- The above script will output 3. By declaring $a and $b global within the function, all references to either variable will refer to the global version. There is no limit to the number of global variables that can be manipulated by a function. (Is it a good idea to use globals in this way?)
User Defined Functions (7)
- arguments - functions expect arguments to be preceded by a dollar sign ($)
and these are usually passed to the function as values - if an argument has a & sign in front - it is treated as a
reference - the following example shows an argument passed as reference <?php
function strip_commas(&$text){
$text = str_replace(",", "", $text);
}
$my_number = "10,000";
stripCommas($my_number);
print($my_number);
?>
User Defined Functions (8)
- default values - a function can use a default value in an argument using the = sign to precede the
argument - consider the following example <?php function setName($FirstName = "John", $LastName = "Smith"){ return "Hello, $FirstName $LastName!\n";
} ?>
- So, to greet someone called John Smith, you would just use: setName();
- To greet someone called Tom Davies, you would use: setName("Tom", "Davies");
- To greet someone called Tom Smith, you would use:setName("Tom");
User Defined Functions (9)
• recursive functions (1)- recursive functions are functions that call themselves (self-calling) or to be sung to the tune of "When the Moon Hits Your Eye": "When a function calls a function in a Turing machine ... that's recu-u-u-u-ursion!" or to put it simply: recursion means anything that references itself.
- compare with iteration - example of iteration (print out all the values of an array)
<?phpfor ($i = 0; $i < sizeof($array); $i++) { print $array[$i]; }
?>
User Defined Functions (10)
• recursive functions (2)- Mathematically speaking, a factorial (denoted by "!") is the result of a number multiplied by all positive integers less than that number. Non-integer and negative values are considered undefined. Zero factorial (0!), however, is defined as 1. e.g. 6! = 6 * 5 * 4 * 3 * 2 * 1 or 720
<?php function factorial($number) {
if ($number < 2) { return 1; } else { return ($number * factorial($number-1)); } } print factorial(6);
?>
User Defined Functions (11)
run code
• anonymous functions (run-time or dynamically created functions)- it is possible for PHP to use the value of an input (e.g. from a form) and change the definition of a function based on the input - example using calculator (last week’s workshop)
<?php
$add = create_function('$a,$b', 'return $a + $b;');
$subtract = create_function('$a,$b', 'return $a - $b;');
$multiply = create_function('$a,$b', 'return $a * $b;');
$divide = create_function('$a,$b', 'return $a / $b;');
extract($_GET);
$fn = ${$op};
echo "$x $op $y = " . $fn($x,$y);
?>
- Note the above example also illustrates how you can store a function name in a variable.
User Defined Functions (12)
• DB connectivity and processing
• forms processing
• sessions & cookies
next week …
Top Related