Chapter 2-5 PHP Functions
Chapter 2-5 PHP Functions
CHAPTER 2:
PHP Functions (5 of 5)
Topics covered:-
Functions
Optional parameters and default values
Global variables
Superglobal arrays
Static variables
Working with reference
Introduction to Functions
• Also called subroutine or methods.
• It contains a block of code that perform a specific task.
• A function can accepts one or more arguments. These
arguments can be of value type or reference type.
• A function can optionally return values.
• Can you elaborate why functions are so important and useful
in any programming languages?
• Note: Since you have learnt C programming language to
declare, define and call function, the concept is also the same
in PHP.
Functions
• Function declaration and definition.
• Syntax:
functionName (arg1, arg2, arg3, …){
//optional return statement
//if the function does return a value
return
}
• Function call that returns a value.
• Syntax:
$valueReturned = functionName(arg1, arg2, arg3, …);
functionName(arg1, arg2, arg3, …);
function displayCount(){
global $count;
echo $count;
}
displayCount(); // display 7
function displayCount(){
echo $GLOBALS["count"];
}
No dollar ($) symbol
displayCount(); //display 10
Static Variables
• Variables declared in a function often been wiped off when the function exit.
• Sometimes, it is often useful to retain local variables’ values even after the
function ends.
• In order to preserve local variables’ values, use static keyword.
• Example:
function displayCounter(){
static $count = 0;
return ++$count;
}
echo "I have counted to : " . displayCounter() . "<br>";
echo "I have counted to : " . displayCounter() . "<br>";
echo "I have counted to : " . displayCounter() . "<br>";
echo "I have counted to : " . displayCounter() . "<br>";
echo "I have counted to : " . displayCounter() . "<br>";
AMIT 2043 Web Systems and Technologies
PHP Functions (Part 5 of 5) Slide 9
$counter = 0;
++$counter;
++$counter;
++$counter;
++$counter;
echo $counter; //display 4
resetCounter($counter); //display 0
echo $counter;
AMIT 2043 Web Systems and Technologies
PHP Functions (Part 5 of 5) Slide 11
function &ref(){
global $count;
return $count;
}
$countNext = &ref();
$countNext++;
echo $count;
echo $countNext;
• Guess the answer returned by the two echo statement.
AMIT 2043 Web Systems and Technologies