php unit II notes
php unit II notes
A function is a block of code written in a program to perform some specific task. The function is a self-
contained block of statements that can repeatedly be executed whenever we need it.
There are two types of functions.
Built-in Function
PHP has a huge collection of internal or built- in functions that you can call directly within your
PHP scripts to perform a specific task, like gettype(), print_r(), var_dump, etc.
User Defined Functions
PHP allows us to create our own customized functions called the user-defined functions.
Using this we can create our own packages of code and use it wherever necessary by simply calling it.
Advantages of Functions
Code Reusability: PHP functions are defined only once and can be invoked many times, like in other
programming languages.
Less Code: It saves a lot of code because you don't need to write the logic many times. By the use of
function, you can write the logic only once and reuse it.
Easy to understand: PHP functions separate the programming logic. So it is easier to understand the flow
of the application because every logic is divided in the form of functions.
Easier error detection: Since, our code is divided into functions, we can easily detect in which function,
the error could lie and fix them fast and easily.
Easily maintained: If anything or any line of code needs to be changed, we can easily change it inside the
function.
Defining a Function
Syntax :
function functionName()
{
// Code to be executed
}
The declaration of a user-defined function start with the word function, followed by the name of the
function you want to create followed by parentheses i.e. () and finally place our function's code between
curly brackets {}. Function names are case-insensitive.
Example :
<?php
function myFunction()
{
echo "Example of PHP function";
Page | 1 C. P. Bhamare
}
myFunction();
?>
Function Arguments
We can pass the information in PHP function through arguments which is separated by comma. PHP
supports Call by Value (default), Call by Reference, Default argument values and Variable-length
argument list.
Arguments are specified after the function name, inside the parentheses. We can add as many arguments as
we want, just separate them with a comma. These are used to hold the values executable during runtime.
Syntax:
function function_name($first_parameter, $second_parameter)
{
// executable code;
}
Example :
<?php
function addFunction($number, $number)
{
$number = $number + $number;
echo "The sum of two numbers is : $number"; //Outputs as 30
}
addFunction(10, 20);
?>
Page | 2 C. P. Bhamare
setDetails("John");
?>
Returning Values from Functions
Functions can also return values to the part of program from where it is called. The return keyword is used
to return value back to the part of program, from where it was called. The returning value may be of any
type including the arrays and objects. The return statement also marks the end of the function and stops the
execution after that and returns the value.
<?php
// function along with three parameters
function getProduct($num1, $num2, $num3)
{
$product = $num1 * $num2 * $num3;
return $product; //returning the product
}
// storing the returned value
$result = getProduct(2, 3, 5);
echo "The product is $result";
?>
A function can not return multiple values. However, you can obtain similar results by returning an array, as
demonstrated in the following example.
<?php
// Defining function
function divideNumbers($dividend, $divisor){
$quotient = $dividend / $divisor;
$array = array($dividend, $divisor, $quotient);
return $array;
}
// Assign variables as if they were an array
list($dividend, $divisor, $quotient) = divideNumbers(10, 2);
echo $dividend; // Outputs: 10
echo $divisor; // Outputs: 2
echo $quotient; // Outputs: 5
?>
Call By Reference
Value passed to the function doesn't modify the actual value by default (call by value). But we can do so
by passing value as a reference.
Page | 3 C. P. Bhamare
By default, value passed to the function is call by value. To pass value as a reference, we need to use
ampersand (&) symbol before the argument name.
<?php
function setValue(&$num)
{
$num = $num + 2;
}
$n = 5;
echo $n;
setValue($n);
echo $n;
?>
Variable Scope
The location of the declaration determines the extent of a variable's visibility within the PHP program i.e.
where the variable can be used or accessed. This accessibility is known as variable scope.
By default, variables declared within a function are local and they cannot be viewed or manipulated from
outside of that function, as demonstrated in the example below:
<?php
function test()
{
$greet = "Hello World!";
echo $greet;
}
test(); // Outputs: Hello World!
echo $greet; // Generate undefined variable error
?>
global Keyword
There may be a situation when you need to import a variable from the main program into a function, or
vice versa. In such cases, you can use the global keyword before the variables inside a function. This
keyword turns the variable into a global variable, making it visible or accessible both inside and outside the
function, as show in the example below:
<?php
$greet = "Hello World!";
// Defining function
function test(){
Page | 4 C. P. Bhamare
global $greet;
echo $greet;
}
Variable Function
PHP supports the concept of variable functions means that we can call function based on value of a
variable. 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
The variable function does not work with echo( ),print( ),unset( ), isset( ). PHP allows us to store a name of
a function in a string variable and use the variable to ca ll the function.
<?php
function add($x, $y){
echo $x+$y;
}
function sub($x, $y){
echo $x-$y;
}
$var=add;
$var(10,20); // 30
$var=sub;
$var(10,20); // -10
?>
Anonymous Function
Anonymous function is a function without any user defined name. Such a function is also
called closure or lambda function.
Page | 5 C. P. Bhamare
$var = function ($arg1, $arg2, ..$argN) { // code to executed };
Since the function doesn’t have a name, you need to end it with a semicolon (;) because PHP treats it as an
expression. This anonymous function is not useful at all because you cannot use it like a named function.
To use an anonymous function, you need to assign it to a variable and call the function via the variable.
Example 1)
<?php
$multiply = function ($x, $y) {
return $x * $y;
};
echo $multiply(10, 20);
output
200
Example 2)
<?php
$var = function ($x) {return pow($x,3);};
echo "cube of 3 = " . $var(3);
?>
output
cube of 3 = 27
Page | 6 C. P. Bhamare