Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 23

Hidaya Institute Of Science &

Technology

Functions in PHP
Lecture 1

MYL
07/18/23 1
Contents

What are functions


Why functions
Reusing PHP script
Types of functions
Function parts
Variables scope
Parameter manipulation
Function returning values

07/18/23 2
What is Function
A function is a block of organized, reusable code that is used
to perform a single, related action.
A function is a self-contained piece of code which carries out
a particular task.
 A key benefit of using functions is that they are reusable; if
you have a task that needs to be performed a number of
times, a function is an ideal solution.
Functions provides a high degree of code reusing and better
understating of code for the programmers.
You have already seen various functions like str_count(),
range() etc.

07/18/23 3
Function Or Not To Function
Organize your code into “paragraphs” - capture a complete
thought and “name it”

Don’t repeat yourself - make it work once and then reuse it

If something gets too long or complex, break up it into the


logical chunks and put those chunks in functions (explained
later)

Make a library of common stuff that you do over and over -


perhaps share this with your friends...

07/18/23 4
07/18/23 5
calculateArea get window height
get window width
calculate area
store area
Do calculation
createMessage Check value
Output message
Get image position
Calculate new value
Set image position
Change text color
If position correct
animateImage output message

07/18/23 6
Reusing PHP code
Often scripts need to perform the same actions in several
different locations in the script.
It may even be the case that you use the same code in
different scripts.
If you find yourself typing the same ten lines of code over
and over (or cutting and pasting it repeatedly).
 you can move that code into a separate file and get it from
that file whenever you need it.
You can reuse code in two ways: by inserting a file containing
code into a script or by writing and calling a function.

07/18/23 7
Types of functions

There are two types of functions


1.Built-in or Predefined :
 Functions provided by the language itself.
One of the cool features of PHP is the huge collection of built-in
functions it provides.
You can call these functions anywhere in your scripts without
defining (advantage)

2.Custom or User defined :


 Functions specified by users according to their requirement.

07/18/23 8
How to write & call a function in PHP

name
myFunction
function createMessage
calcuateScore
animateImage
hideMenu () {
echo “This code is inside the function”;

// loops, if statements, anything!

//sometime latter
myFunction();
If it’s in function, it won’t
myFunction(); run unless you call it
myFunction();
07/18/23 9
Function Names
Same rules applied for variable names are applied for function
names. That is, they can only contain letters, numbers and
underscore and, should begin only with a letter or an underscore.

Note: the function names are case insensitive. It means you can also
call myfunction() as:
MYFUNCTION()
MyFunction();

Make sure you don’t define custom functions with names of built-
in functions

07/18/23 10
Where To Declare Functions

function myFunction(){
//lots of code
myOtherFunction();
}

function myOtherFunction(){
//lots of code
}

myFunction();

07/18/23 11
Variables Scope
Scope can be defined as the range of availability a variable has to the
program in which it is declared. PHP variables can be one of four
scope types.

i. Local Variable
ii. Global Variable
iii. Static Variable
iv. Function Parameters

07/18/23 12
i) Local Variables
A variable declared within a PHP function is local and can only be accessed within
that function. (the variable has local scope):
<?php
$a = 5; // global scope
function myTest() {
echo $a; // local scope
}
myTest();
?>
The script above will not produce any output because the echo statement refers to
the local scope variable $a, which has not been assigned a value within this scope.

You can have local variables with the same name in different functions, because
local variables are only recognized by the function in which they are declared.

Local variables are deleted as soon as the function is completed.

07/18/23 13
ii) Global Variables
Global scope refers to any variable that is defined outside of any function.

Global variables can be accessed from any part of the script that is not inside a
function.

To access a global variable from within a function, use the global keyword:
<?php
$a = 15; $b = 10;
function myTest() {
global $a, $b;
$b = $a + $b;
}
myTest();
echo $b;
?>

The script above will output 25.


07/18/23 14
ii) Global Variables (cont.)
PHP also stores all global variables in an array called $GLOBALS[index].

Its index is the name of the variable. This array is also accessible from within
functions and can be used to update global variables directly.

The example above can be rewritten as this:


<?php
$a = 15; $b = 10;
function myTest() {
$GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
}
myTest();
echo $b;
?>

The script above will output 25.


07/18/23 15
iii) Static Variables
When a function is completed, all of its variables are normally deleted. However,
sometimes you want a local variable to not be deleted.

To do this, use the static keyword when you first declare the variable:

static $rememberMe;

Then, each time the function is called, that variable will still have the information it
contained from the last time the function was called.

Note: The variable is still local to the function.

07/18/23 16
iv) Function Parameters
A parameter is a local variable whose value is passed to the function by the calling
code.

Parameters are declared in a parameter list as part of the function declaration:

function myTest($para1,$para2,...) {

// function code

07/18/23 17
Passing values to a functions
You can pass values to a function by putting the values between the parentheses
when you call the function

functionname(value1,value2,...);

The function statement includes variable names for the values it’s expecting,
as follows:

function functionName($varname1,$varname2,...)
{
statements
}

Note: However you have to be careful about arguments order

07/18/23 18
Passing values in the correct order
The function receives the values in the order they are passed.

function functionx($x, $y, $z)


{
//do stuff
Parameters
}

You call the function as follows:

functionx($var1, $var2, $var3);

Arguments
The function sets:
$x=$var1, $y=$var2, and $z=$var3.

07/18/23 19
Passing the right number of values
 A function is designed to expect a certain number of
values to be passed to it.

 If you don’t pass enough values (arguments), the function


sets the missing one(s) to default value (if you specified)
other wise it will gives you a error.

 If you send too many values, the function will simply


ignore the extra values.

07/18/23 20
Default value of parameter
 You can set default values to be used when a value isn’t
passed.

 The defaults are set when you write the function.

function add_2_numbers($num1=1, $num2=1)


{
echo $total = $num1 + $num2;
}

add_2_numbers(5,5)
add_2_numbers(5);
add_2_numbers();
07/18/23 21
Function return value
 Often a function will take arguments in its parameters, will
do some computation and return a value to be used as the
value in the calling expression.
 Return value is the final value you expect from a function
after executing code inside it.
 If you don’t specifically return a value in your function
then its return value will be NULL.
 The return keyword is used for this.
function sum ($value1, $value2)
{
$result = $value1 + $value2;
return $result;
}
echo sum();
07/18/23 22
Assignments
i) Make user defined function of the following like built in function:
a) strtoupper
b) implode
c) explode
d) strlen
e) strrev
f) range

ii) Convert the following assignments into functions:


a) Sorting
b) Calculator in switch
c) marksheet
d) Array sum

07/18/23 23

You might also like