0% found this document useful (0 votes)
19 views5 pages

Chapter 2.4

php

Uploaded by

34Shreya Chauhan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views5 pages

Chapter 2.4

php

Uploaded by

34Shreya Chauhan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

2.

4 Function and its type- User defined function,variable function and anonymous function

Function :
A function is a named block of code that performs a specific task, possibly acting upon a set of values given
to it, or parameters, and possibly returning a single value.
Advantages of using function :
1. Functions save on compile time i.e no matter how many times you call them, functions are compiled only
once for the page.
2. Functions also improve reliability by allowing you to fix any bugs in one place, rather than everywhere
you perform a task.
3. Function improve readability by isolating code that performs specific tasks.

Defining a Function :
The function name can be any string that starts with a letter or underscore followed by zero or more letters,
underscores, and digits.
Syntax : function function_name([parameters if any])
{
Function body
}
Example:
<?php
function display() // declare and define a function
{
echo "Hello,Welcome to function";
}
display(); // function call
?>
When a function is defined in a script, to execute that function, programmer have to call it with its name and
parameters if required.

Calling a Function :
Functions in a PHP program can be built-in or user-defined. Regardless of their source, all functions are
executed in the same way:
Syntax: $Variable = function_name( [ parameters if any ] );
- If a function returns any value then it is stored in $variable.
- name of the function
- The number of parameters a function requires differs from function to function . The parameters
supplied to the function may be any valid expression and must be in the specific order expected by
the function.
Example: display( );

A function with return value :


Functions may return some value. To return a value from a function, use the return statement. When a return
statement is encountered during execution, control reverts to the calling statement, and the evaluated results
of expression/function will be returned as the value of the function. one can include any number of return
statements in a function.
To declare a return type for the function value, add a colon ( : ) at the end of function declaration line
followed by data type of return value.
Syntax : function function_name([parameter if any]) : returntype
{
Statement body;
Return varaible_name/expression;
}
Example :
<?php
function addition():int
{
$a=2;
$b=3;
$c=$a+$b;
return $c ;
}
echo "addition =" .addition();
?>
Output : addition =5

A function with arguments/parameters : (Pass by value method)


Data can be passed to functions through arguments. An argument passed to a function is like a variable that
holds data. Arguments are specified after the function name, inside the parentheses. One can add N number
of arguments separated with a comma in the function argument list. In PHP, arguments are usually passed
by value, which means that a copy of the value is used in the function.
Syntax : function function_name($argument 1,$argument 2, … ,$argument N)
{
Function body;
}
Example :
<?php
function addition($a,$b):int
{
$c=$a+$b;
return$c ;
}
echo "addition =" .addition(10,25);
?>
Output : addition = 35

A function with arguments/parameters : (Pass by reference method)


When a function argument is passed by reference, changes to the argument also change the variable that was
passed in. To turn a function argument into a reference, the & operator is used:
Syntax : function function_name(&$argument1,&$argument2, … , &$argument N)
{
Function body;
} Copy variable is not been created
Example : so the changes are made directly in
<?php
function add_five(&$no) the variable itself.
{
$no=$no+5;
}
$num=5;
add_five($num);
echo "Number =" .$num;
?>
Output : Number =10

Variable Scope :
Any variable a programmer create in a script can be used anywhere in a page,if a function is not used a
script. Functions keep their own sets of variables that are distinct from those of the page and of other
functions. The variables defined in a function, including its parameters, are not accessible outside the
function, and, by default, variables defined outside a function are not accessible inside the function. Scope of
variable specify accessibility of variable in a script.
Local scope : A variable defined inside a function is local to that function. It can not be accessed from
outside the function.
Global scope : A variable defined outside all function is called as global variable and can be accessed from
anywhere in the script.Global variable can be defined with global keyword placed before the variable.
Example:
<?php
$v1=5;
function display()
{
$v2=10;
echo "<br> v1= ".$v1;// defined outside function
echo "<br> v2= ".$v2;
}
display();
echo "<br> v1= ".$v1;
echo "<br> v2= ".$v2; // defined inside display function
?>
Output :
Notice: Undefined variable: v1 in C:\xampp\htdocs\function.php on line 8
v1=
v2= 10
v1= 5
Notice: Undefined variable: v2 in C:\xampp\htdocs\function.php on line 13
v2=

Example of global :
<?php
$v1=5;
function display()
{
$v2=10;
global $v1;
echo "<br> v1= ".$v1;
$v1=15;
echo "<br> v2= ".$v2;
}
display();
echo "<br> v1= ".$v1;
echo "<br> v2= ".$v2;
?>
Output :
v1= 5
v2= 10
v1= 15
Notice: Undefined variable: v2 in C:\xampp\htdocs\function.php on line 15
v2=

Static Variables :
PHP supports declaring function variables as static. A static variable retains its value between all calls to the
function and is initialized during a script’s execution only the first time the function is called. A static
keyword is used to declare a function variable static.
Syntax: static var [= value];
Example :
<?php
function counter()
{
static $count = 1;
return $count++;
}
for ($i = 1; $i <= 5; $i++) {
print counter();
}
?>
When the function is called for the first time, the static variable $count is assigned a value of 1. The value is
returned and $count is incremented. When the function ends, variable $count is retained in the memory, and
its value remains the same until the next time counter() is called. The for loop displays the numbers from 1
to 5.

Variable Functions :
If name of a variable has parentheses (with or without parameters in it) in front of it, PHP parser tries to find
a function whose name corresponds to value of the variable and executes it. Such a function is called
variable function. This feature is useful in implementing callbacks, function tables etc.
Example: In following example, display() function is assigned to var1.When var1 is called with parenthesis
it becomes a function variable that matches its value with function name and executes the function.
Example :
<?php
function display()
{
echo "Hello world";
}
$var1="display";
$var1(); // var1 is a function variable
?>
Output : Hello world

Example 2:
<?php
function add($x, $y)
{
echo $x+$y;
}
$var1="add";
$var1(10,20);
?>
Output : 30

Anonymous Functions :
Anonymous function is a function without any user defined name. Such a function is also
called closure or lambda function. Sometimes, you may want a function for one time use. Closure is an
anonymous function which closes over the environment in which it is defined. Most common use of
anonymous function to create an inline callback function.
Syntax: $var=function($arg1,$arg2) {return $val;};
There is no function name between the function keyword and the opening parenthesis.There is a semicolon
after the function definition because anonymous function definitions are expressions. Function is assigned to
a variable, and called later using the variable’s name.When passed to another function that can then call it
later, it is known as a callback. Return it from within an outer function so that it can access the outer
function’s variables. This is known as a closure.
Example:
<?php
$var1=function($x){return pow($x,3);};
echo "cube of 3=" .$var1(3);
?>
Output :cube of 3=27

Anonymous function as callback :


In following example, an anonymous function is used as argument for a built-in usort() function. The usort()
function sorts a given array using a comparison function.
Example :
<?php
$arr = [10,3,70,21,54];
usort ($arr, function ($x,$y){return $x>$y;});foreach($arr as $x){echo "$x<br>";}
?>
Output : 3
10
21
54
70
Anonymous function as closure
Closure is also an anonymous function that can access variables outside its scope with the help of use
keyword.
Example :
<?php
$maxmarks=300;
$percent=function ($marks) use ($maxmarks) {return $marks*100/$maxmarks;};
echo "marks=285 percentage=". $percent(285);
?>
Output :
marks=285 percentage=95

You might also like