Introduction
Functions are
the most important part of any programming language, PHP included. You can say
in a few words that functions are pieces of code that accept values and produce
results.
Function is a block of code that is not immediately
executed, but can be called by your scripts when needed. Functions can either
be built-in or defined by the user. The real power of PHP comes from its
functions. In PHP, there are more than 700 built-in functions.
Functions help you create organized and
reusable code. They allow you to abstract out details so your code becomes more
flexible and more readable. Without functions, it is impossible to write easily
maintainable programs because you're constantly updating identical blocks of
code in multiple places and in multiple files.
Declare function
To declare a function, use the “function” keyword, followed by the name of the
function and any parameters in parentheses. To invoke a function, simply use
the function name, specifying argument values for any parameters to the
function. If the function returns a value, you can assign the result of the
function to a variable.
Syntax: function
<name of the function>([mixed $....]) { }
Example:
<?php
// Function Declaration
function myFunction() //no
semicolon here!
{
print “<h1>This is my
first function</h1>”;
}
// Call Function
myFunction();
?>
Note:
Ø Function names are case-insensitive, though it
is usually good form to call functions as they appear in their declaration.
Ø All functions in PHP have the global scope - they can be called
outside a function even if they were defined inside and vice versa.
Ø Your function name can start with a letter or underscore
"_", but not a number!
Variable Scope
Up to now you
can used declared any variable anywhere in a page. With functions this is no
longer always true. Functions keep their sets of variables that are distinct
from those of the page and of page and of other functions.
The Variables
defined in a function, including its parameters, are not accessible outside of
the function, and by default, variables defined outside a function are not
accessible inside the function.
<?php
$text='Hey I’m in a pag';
?>
<P>this is a web page<P>
<?php
echo
$text;
?>
<BR>
<?php
$a=3;
function Add()
{
$a+=2;
echo $a.'<BR>';
}
Add();
echo $a;
?>
Global Variable
If you want a variable in the
global scope be accessible with in a function, you can use the global keyword.
<?php
$a=3;
function
Add()
{
global
$a;
$a+=2;
echo
$a;
}
Add();
echo
$a;
?>
You must include the global
keyword in a function before any uses of
the global variable or variables you want to access. Because they are declared
before the body of the function, Function parameters can never be globale.
Static Variables
Static variable is shared
between all calls to the functions and it is initialized only the first time
the function is, called.
Use static keyword to declare a
static variable.
<?php
Function counter(){
static $count=0;
return $count++;
}
for($i=0;$i<=5;$i++)
{
echo counter ();
}
?>
Function arguments
Information may be passed to functions via
the argument list, which is a comma-delimited list of expressions.
PHP supports passing arguments by value
(the default), passing by reference, and default argument values. Variable-length
argument lists are also supported
Inside the function, it doesn't matter
whether the values are passed in as strings, numbers, arrays, or another kind
of variable. You can treat them all the same and refer to them using the names
from the prototype.
You don't need to (and, in fact, can't)
describe the type of variable being passed in PHP keeps track of this for you.
Making arguments be passed by value
All values being passed into and out of a
function are passed by value, not by reference. This means PHP makes a copy of
the value and provides you with that copy to access and manipulate. Therefore,
any changes you make to your copy don't alter the original value.
<?php
// Function Declaration
function printName($name) //no semicolon
here!
{
echo "Name is ".$name;
}
// Call Function with pass parameters by values
printName(“saman”);
?>
Making arguments be passed by reference
By default, function arguments are passed
by value (so that if the value of the argument within the function is changed, it
does not get changed outside of the function). To allow a function to modify
its arguments, they must be passed by reference.
To have an argument to a function always
passed by reference, prepend an ampersand (&) to the argument name in the
function definition:
<?php
function add_some_extra(&$string)
{
$string .= 'and something extra.';
}
$str = 'This is a string, ';
add_some_extra($str);
echo $str;
// outputs 'This is a string, and something extra.'
?>
Default argument values
<?php
//Function Declaration
//Parameters with Default values
function Mult($num1, $num2 = 1)
{
echo "$num*$num2";
}
//Function call with default argument
Mult(5);
//Function call with values
Mult(5,12);
?>
Exercise:
Define
a function that takes 2 parameters (String and character representing text
effect) and prints in that string with the text effect.
Default text effect should be “Bold”. If user wants, he
can pass character for “Italics” and “Underline” too.
Creating Functions That Take a Variable Number of Arguments
Method 1: Using Arrays
function total($numbers) {
// initialize to avoid warnings
$sum = 0;
// the number of elements in the array
$size = count($numbers);
// iterate through the array and add up the
numbers
for ($i = 0; $i < $size; $i++) {
$sum += $numbers[$i];
}
return $sum;
}
$tot = total(array(96, 93, 97));
Method 2: Using functions
function total() {
// initialize to avoid warnings
$sum = 0;
// the number of arguments passed to the
function
$size = func_num_args();
// iterate through the arguments and add up
the numbers
for ($i = 0; $i < $size; $i++) {
$sum += func_get_arg($i);
}
return $sum;
}
$tot = total(96, 93, 97);
This example uses a set of
functions that return data based on the arguments passed to the function they
are called from. First, func_num_args(
) returns an integer with the number of arguments passed into its
invoking function.
From there, you can then call func_get_arg( ) to find the
specific argument value for each position.
Exercise
5
Extend above to methods to get return the average of set of
numbers.
Returning More Than One Value
Return an array and use list( ) to separate elements.
function
time_parts($time) {
return
explode(':', $time);
}
list($hour,
$minute, $second) = time_parts('12:34:56');
You pass in a time string as you
might see on a digital clock and call explode( ) to break it apart as array
elements. When time_parts( ) returns, use list( ) to take each element and
store it in a scalar variable.
If you want, You can also use
global variables.
function time_parts($time) {
global $hour, $minute, $second;
list($hour, $minute, $second) = explode(':',
$time);
}
time_parts('12:34:56');
Skipping Selected Return Values
A function returns multiple
values, but you only care about some of them.
Omit variables inside of list(
)
function
time_parts($time)
{
return
explode(':', $time);
}
list(, $minute,)
= time_parts('12:34:56');
Exercise
Extend the above example so that
time part HOURS get returned and to display some greeting message based on the
time. Eg: if hrs<12, Good Morning.
Calling Variable Functions
function eat_fruit($fruit)
{
print "chewing $fruit.";
}
$function = 'eat_fruit';
$fruit = 'kiwi';
$function($fruit); // calls eat_fruit( )
Exercise
Define three different functions that take two
numbers as input parameters and print addition, subtraction and multiplication
respectively.
Outside to functions, do following steps.
Declare two variables and assign them with
10 &15.
Generate random number.
HINT: To
generate a random number between two end points, pass mt_rand( ) two arguments:
$random_number = mt_rand(1, 100);
If random number is <20, you should get
printed the addition of above two numbers (10 &15)
If 20<=random number <50, you should
get printed the substraction of above two numbers (10 &15)
If random number is >50, you should get
printed the multiplication of above two numbers (10 &15)
RULE: YOU CAN USE ONLY ONE FUNCTION CALL
INSIDE YOUR PROGRAM.
Creating Dynamic Functions
Use create_function( )
$add =
create_function('$i,$j', 'return $i+$j;');
$add(1, 1); //
returns 2
The first parameter to create_function( ) is a
string that contains the arguments for the function, and the second is the
function body.
Internal (built-in) functions
Date manipulation function
Get Current date (date() function)
<?php
$today = date("F j, Y");
echo "$today";
$today = date("d / M/ Y");
echo "$today";
?>
Write a program to get the date in 12th December
2008 like?
<?php
// Assuming today is: March 10th, 2001, 5:16:18 pm
$today = date("F j, Y, g:i a"); // March 10, 2001, 5:16 pm
$today = date("m.d.y"); // 03.10.01
$today = date("j, n, Y"); // 10, 3, 2001
$today = date("Ymd"); // 20010310
$today = date('h-i-s, j-m-y, it is w Day z '); // 05-16-17, 10-03-01, 1631 1618 6 Fripm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.'); // It is the 10th day.
$today = date("D M j G:i:s T Y"); // Sat Mar 10 15:16:08 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h'); // 17:03:17 m is month
$today = date("H:i:s"); // 17:16:17
?>
// Assuming today is: March 10th, 2001, 5:16:18 pm
$today = date("F j, Y, g:i a"); // March 10, 2001, 5:16 pm
$today = date("m.d.y"); // 03.10.01
$today = date("j, n, Y"); // 10, 3, 2001
$today = date("Ymd"); // 20010310
$today = date('h-i-s, j-m-y, it is w Day z '); // 05-16-17, 10-03-01, 1631 1618 6 Fripm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.'); // It is the 10th day.
$today = date("D M j G:i:s T Y"); // Sat Mar 10 15:16:08 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h'); // 17:03:17 m is month
$today = date("H:i:s"); // 17:16:17
?>
Find dates in
the future or the past
<?php
$tomorrow
= mktime(0, 0, 0, date("m")
, date("d")+1, date("Y"));
$lastmonth = mktime(0, 0, 0,
date("m")-1, date("d"),
date("Y"));
$nextyear
= mktime(0, 0, 0, date("m"),
date("d"),
date("Y")+1);
echo
date('d/M/y',$tomorrow)."<br>";
echo
date('d/M/y',$lastmonth)."<br>";
echo
date('d/M/y',$nextyear)."<br>";
?>
Note: This can be more reliable than simply adding or subtracting
the number of seconds in a day or month to a timestamp because of daylight
saving time.
No comments:
Post a Comment