You are on page 1of 33

PHP FUNCTION

A function is a self-contained block of code that performs a specific task.


A function is a block of statements that can be used repeatedly in a program.
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.
PHP User-Defined Functions
In addition to the built-in functions, PHP also allows you to define your own functions. It is a
way to create reusable code packages that perform specific tasks and can be kept and
maintained separately form main program.
Advantages of using functions:
• Functions reduces the repetition of code within a program :Function
allows you to extract commonly used block of code into a single
component. Now you can perform the same task by calling this function
wherever you want within your script without having to copy and paste the
same block of code again and again.
• Functions makes the code much easier to maintain :Since a function
created once can be used many times, so any changes made inside a
function automatically implemented at all the places without touching the
several files.
• Functions makes it easier to eliminate the errors : When the program is
subdivided into functions, if any error occur you know exactly what
function causing the error and where to find it. Therefore, fixing errors
becomes much easier.
• Functions can be reused in other application :Because a function is
separated from the rest of the script, it's easy to reuse the same function in
other applications just by including the php file containing those functions.
There are two parts which should be clear to you:
▪ Creating a PHP Function
▪ Calling a PHP Function: A function will be executed by a
call to the function
The basic syntax of creating a custom function can be give with:

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 your function's code between curly
brackets {}.
• While creating a user defined function we need to keep few things in
mind:

1.Any name ending with an open and closed parenthesis is a function.


2.A function name always begins with the keyword function.
3.To call a function we just need to write its name followed by the
parenthesis
4.A function name cannot start with a number. It can start with an alphabet
or underscore.
5.A function name is not case-sensitive.
Eg:

Output
PHP Functions with Parameters
• PHP gives you option to pass your parameters inside a
function. You can pass as many as parameters your like. These
parameters work like variables inside your function. Following
example takes two integer parameters and add them together
and then print them.

Output
PHP Functions returning value
• A function can return a value using the return statement in
conjunction with a value or object. return stops the execution of
the function and sends the value back to the calling code.
• You can return more than one value from a function
using return array(1,2,3,4).
• Following example takes two integer parameters and add
them together and then returns their sum to the calling
program. Note that return keyword is used to return a value
from a function.
Output
Passing Arguments by Reference
• It is possible to pass arguments to functions by reference. This
means that a reference to the variable is manipulated by the
function rather than a copy of the variable's value.
• Any changes made to an argument in these cases will change
the value of the original variable. You can pass an argument by
reference by adding an ampersand to the variable name in
either the function call or the function definition.
Output
PHP Function arguments: Passing arrays to
functions

Output
Variable Number of Arguments
By using the ... operator in front of the function parameter, the function accepts an unknown number of
arguments. This is also called a variadic function.The variadic function argument becomes an array.
Example
A function that do not know how many arguments it will get:
function sumMyNumbers(...$x) {
$n = 0;
$len = count($x);
for($i = 0; $i < $len; $i++) {
$n += $x[$i];
}
return $n;
}

$a = sumMyNumbers(5, 2, 6, 2, 7, 7);
echo $a;
Recursive Functions
• A recursive function is a function that calls itself again and again until
a condition is satisfied. Recursive functions are often used to solve
complex mathematical calculations, or to process deeply nested
structures.

Output
PHP is a Loosely Typed Language
• In the example above, notice that we did not have to
tell PHP which data type the variable is.
• PHP automatically associates a data type to the
variable, depending on its value.
<?php
function addNumbers(int $a, int $b) {
return $a + $b;
}
echo addNumbers(5, "5 days");
// since strict is NOT enabled "5 days" is changed
to int(5), and it will return 10
?>
To specify strict we need to set declare(strict_types=1);. This must be on the
very first line of the PHP file.In the following example we try to send both a
number and a string to the function, but here we have added the strict
declaration:
<?php declare(strict_types=1); // strict requirement

function addNumbers(int $a, int $b) {


return $a + $b;
}
echo addNumbers(5, "5 days");
// since strict is enabled and "5 days" is not an integer, an error will be
thrown
?>
PHP superglobal
Several predefined variables in PHP are "superglobals", which
means that they are always accessible, regardless of scope - and
you can access them from any function, class or file without
having to do anything special.
The PHP superglobal variables are:
• $GLOBALS
• $_SERVER
• $_REQUEST
• $_POST
• $_GET
• $_FILES
• $_ENV
• $_COOKIE
• $_SESSION
PHP $GLOBALS
• $GLOBALS is a PHP super global variable which is used
to access global variables from anywhere in the PHP
script (also from within functions or methods).
• PHP stores all global variables in an array called
$GLOBALS[index]. The index holds the name of the
variable.
Output
PHP $_SERVER
• $_SERVER is a PHP super global variable which holds
information about headers, paths, and script locations.

Output
The following table lists the most important
elements that can go inside $_SERVER
PHP $_REQUEST
• PHP $_REQUEST is a PHP super global variable which is used to
collect data after submitting an HTML form.
• The example below shows a form with an input field and a
submit button. When a user submits the data by clicking on
"Submit", the form data is sent to the file specified in the action
attribute of the <form> tag. In this example, we point to this file
itself for processing form data. If you wish to use another PHP
file to process form data, replace that with the filename of your
choice. Then, we can use the super global variable $_REQUEST
to collect the value of the input field:
Output
PHP $_POST
• PHP $_POST is a PHP super global variable which is used to collect form data
after submitting an HTML form with method="post". $_POST is also widely
used to pass variables.
• The example below shows a form with an input field and a submit button.
When a user submits the data by clicking on "Submit", the form data is sent
to the file specified in the action attribute of the <form> tag. In this example,
we point to the file itself for processing form data. If you wish to use another
PHP file to process form data, replace that with the filename of your choice.
Then, we can use the super global variable $_POST to collect the value of the
input field.
PHP $_GET

• _GET : $_GET is a super global variable used to collect data from the
HTML form after submitting it. When form uses method get to
transfer data, the data is visible in the query string, therefore the
values are not hidden. $_GET super global array variable stores the
values that come in the URL. GET is used to request data from a
specified resource.
Eg.
OUTPUT
$_FILES is a super global variable which can be used to upload
files. Here we will see an example in which our php script checks
if the form to upload the file is being submitted and generates a
message if true.
OUTPUT

THEN CLICK SUBMIT BUTTON


• $_ENV is used to return the environment variables from the web
server.
• $_COOKIE
Cookies are small text files loaded from a server to a client computer
storing some information regarding the client computer, so that when
the same page from the server is visited by the user, necessary
information can be collected from the cookie itself, decreasing the
latency to open the page.
• $_SESSION
Sessions are wonderful ways to pass variables. All you need to do is
start a session by session_start();Then all the variables you store
within a $_SESSION, you can access it from anywhere on the server.
OUTPUT

You might also like