Sie sind auf Seite 1von 12

FUNCTIONS

Presented By
Sujata S
(PRN:060341003)
Topics:
• Definition of functions
• Scope of variables
• Function parameters
• Returning values from user defined
functions
• Dynamic function calls
Functions
• A function is a group of PHP statements that
perform a specific task.

• Alternatively it can be said as, a block of code


that is not immediately executed but can be
called when needed.
• Functions can be built-in or user defined
functions.
Defining a function
• Functions are defined as:
function function name($argument 1,$argument 2)
{
//function code here
}
• Functions require information to be passed them
and usually return a value
• Functions require parentheses whether or not
they accept arguments
Scope of variables
• Scope of a variable is defined as the extent to
which a variable can be seen in a program.

• In functions, a variable defined within the


function remains local to that function.

• In order to access variables declared in the


function the scope of the variable has to be
made global.
Scope of variables
• Static variables:
A variable when declared as static is shared
between all calls to the function and is initialized
during script’s execution only first time the
function is called.

• static keyword is used to declare variable as


static
Function parameters
• Pass by value
When we pass arguments to functions they are
stored as copies in parameter variables. Any
changes made to these variables in the body of
the function are local to that function
• Pass by reference
A reference to the variable is manipulated by the
function rather than a copy of variable’s value.
Any changes made to an argument in these
cases will change the value of original variable.
Pass by value
Ex:
<?php
function addfive($num)
{
$num=$num+5;
}
$num1=10;
addfive($num1);
echo ”$num1”;
?>
Pass by reference
Ex:
<?php
function addfive($num) {
$num=$num+5;
}
$num1=10;
addfive(&$num1);
echo “$num1”;
?>
Returning values from user defined
functions
• A function can return a value using the return
statement in conjunction with a value or a object.

• return stops the execution of the function and


sends the value back to the calling code

• return statement can return a value, an object or


even nothing at all.
Dynamic function calls

• These are useful when we want to alter the


program flow according to changing
circumstances i.e. giving call to a function is
based on the data that we have during
execution.

• One way to implement this is by setting a


variable with the name of a function and then
use the variable as if it were a function.
Dynamic function calls
Ex:
<?php
function print_text($text) {
echo”$text”;
}
$var=“print_text”;
$var(“Hello”);
echo ”<br>\n”;
?>

Das könnte Ihnen auch gefallen