Functions In PHP
This article is a continuation of my famous “Fast PHP Tutorials”
series. I had stopped writing for the last, only, 6 years :P, because
of my entrepreneurship ventures. Thank you all my fans and students
around the world for your feedback and support.if(typeof __ez_fad_position != ‘undefined’){__ez_fad_position(‘div-gpt-ad-howtoforge_com-box-3-0’)};
Well, functions
are considered to be a complicated topic in programming and many newbies
think it will cost them a hand and a leg to master them. But mark my
words and mark them well – functions are your friends and they are one
of the easiest and most effective things in programming to learn.if(typeof __ez_fad_position != ‘undefined’){__ez_fad_position(‘div-gpt-ad-howtoforge_com-medrectangle-3-0’)};
REAL WORLD EXAMPLE 1:
Remember
those one minute digital photo labs, they make your photo and give you
set of eight or four photos just with a click. So who is doing the part
where they have to arrange your photo in an image enhancement software
to fix the lighting and contrast, arrange them by four or eight and then
print them? Simple, their software has a “function” that does this all
part when “called” by a click.
SUMMARY:
INPUT: (PHOTO, QUANTITY i.e 4 or 8)
PROCESSING: ENHANCE THE IMAGE’S CONTRAST AND LIGHTING ETC AND PREPARE FOR PRINTING ACCORDING TO THE REQUESTED QUANTITY
OUTPUT: PRINT THE ARRANGED PHOTO AND CUT INTO THE DESIRED QUANTITY.
REAL WORLD EXAMPLE 2:
The
simplest example of functions, in real life, is your simple french
fries cutter. You just have to press the potatoe in it and it converts a
potatoe to maximum possible french fries with a specific size and
shape.if(typeof __ez_fad_position != ‘undefined’){__ez_fad_position(‘div-gpt-ad-howtoforge_com-medrectangle-4-0’)};
SUMMARY:
… can you guess the INPUT, PROCESSING and the OUTPUT of this example?
yes, very good,
INPUT: PUT POTATOE IN THE CUTTER
PROCESSING: SLICE THE POTATOES ACCORDING TO THE PRE-DESIGNED SHAPE AND SIZE
OUTPUT: PRODUCE THE DESIRED FRENCH FRIES.
Let’s jump to the programming world with these concepts of the real world examples.
WHAT IS A FUNCTION?
A set of code / instructions to perform a certain task, when called.
Why we need Functions?
When
you have to perform the same task again and again, you can reuse your
code. Functions also make your code maintenance easy and simple. Code is
an integral part of Object Oriented Programming.
GOOD PROGRAMMING PRACTICE:
A function should perform only one specific task at a time to remove
ambiguity and to make it independent. For example you will be shocked to
buy pizza in starbucks coffee shop 🙂
You see, I told you functions are one of the most easiest things to understand. Now lets learn about Functions in PHP.
In PHP, you define a function as follows:
functionName (INPUT) {
PROCESSING
generate OUTPUT
}
Quick Example of PHP Functions:
Write a function in PHP that prints your website name:
<?php
function printWebsiteName() {
echo "YOUR WEBSITE NAME";
}
?>
You can call this function “anywhere” in your php code as
<?php
printWebsiteName();
?>
I
said, “anywhere” because unlike other strict-programming-languages, in
PHP you do not necessarily define function-body before calling it.
Remember,
try to write your functions to produce the output in the simplest form
to have maximum control on their output or in other words DO NOT MIX
PRESENTATION (HTML / CSS ETC) WITH PROCESSING (PHP). Consider a
situation where you have to print your website name in the same page in
two colours i.e black and white.
One way is to write the formatting code in your function like
<?php
function printWebsiteName() {
// #000 for black colour
echo "<font color='#000'> YOUR WEBSITE NAME </font>" ;
}
?>
It
means for white colour i.e #fff you have to write one more function.
Which means “REDUNDANCY” which is a monster in good programming
practice.
Now consider one more situation where you want to print
your website name in your <title> tags. can you call this above
function? …
Don’t tell me you said YES!… :-s
So lets make one function that returns your website name without any other fuss.
<?php
function printWebsiteName() {
return "Your Website Name";
}
?>
Lets print it WHITE:
<font color='#fff'> <?php echo printWebsiteName(); ?> </font>
For black:
<font color='#000'> <?php echo printWebsiteName(); ?> </font>
To use in title tags:
<title> <?php echo printWebsiteName(); ?> </title>
Did you see the function-call is same but it is doing three different jobs because,
- function does not use Presentation / HTML
- it performs only one task i.e to return website name
Before we go deeper into functions, lets remember a few rules while writing functions in PHP
- function must be started with a KEYWORD “function” before function name
- function name can start with underscore (_) or alphabet but not a number
- all function body code must be inside opening and closing braces ” { } “
//correct
myFuncName() {
}
//correct
_myFuncName() {
}
//incorrect
8myFuncName() {
}
USING PARAMETERS IN FUNCTIONS:
Parameters
are the INPUT. You can pass all PHP data-types as function parameters.
Lets write a function which takes two numbers and display their
additional result,
<?php
function addTwoNumbers($number1, $number2) {
echo $number1 + $number2;
}
//passing two digits in the function call
addTwoNumber(2,2);
Do you know the result of this function call? … hmm, if you said 4, you are wrong, I am afraid.
If
you watch closely, I wrote WRONG function name in the function call. my
function call is addTwoNumber while the function name ends on a ‘s’ i.e
addTwoNumbers
PHP will throw a warning of undefined function.
So let’s make the correct call:
addTwoNumbers(2,2);
Now this one displays 4.
TIP:
some programmers copy-paste function name in its CALL from its
DEFINITION while coding to avoid any typos, which becomes a normal
mistake when working on big projects, especially OOP.
TIP:
to make your code more sensible write meaningful function names e.g
“addTwoNumbers” is a much better function name than “funcadd2”
TIP: “addTwoNumbers” is more readable than “addtwonumbers” or “add2numbers”
It
is always a good programming practice to follow standard programming
tips from start of your learning process to make them your habit.
PASSING ARRAYS TO A FUNCTION:
Passing
arrays to a function as a parameter is same as passing variables. I
already said you can pass any type of PHP DATA TYPE as a function’s
parameter, even image, a file handle, object etc etc
$languages = array('php','asp','C');
function displayLanguages($arrLanguages) {
foreach($arrLanguages as $langName) {
echo $langName . " - ";
} //end foreach
} //end function
TIP: commenting your code can save you alot of time and in your practical life, may be your job.
Let#s call this function now:
displayLanguages($languages);
OPTIONAL PARAMETERS:
Your
function name can have optional parameters i.e it may or may not be
passed from function call. For instance, in the above function you want
to displays all langauges but also display your favorite language
however, it’s optional to send favorite language name.
$languages = array('php','asp','C');
function displayLanguages($arrLanguages,$favorite = NULL) {
foreach($arrLanguages as $langName) {
echo $langName . " - ";
} //end foreach
if ($favorite !== NULL) {
echo "my favorite language is " . $favorite;
} //end if
} //end function
Watch the following two function calls:
//displays only language names
displayLanguages($languages);
/*
displays favorite message as well because now $favorite has string "PHP" in
it and it is no more a NULL
*/
displayLanguages($languages,"PHP");
TIPS ABOUT OPTIONAL PARAMETER:
- you define a default value for your OPTIONAL parameter in your function parameter list.
- always, please concentrate, define your optional parameters on the right most of your parameter list.
To explain the second point here, see the following code:
function myRainbow($red, $green, $blue, $CMYK = 'whatever default value') {
// here CMYK is optional, it may or may not be passed in function call
}
function myRainbow($red, $green, $CMYK = 'whatever default value', $blue) {
// now $CMYK is no more OPTIONAL because there is one mandatory-parameter on its right.
}
TIP: to compare a NULL value you can also use PHP built-in function is_null() but according to benchmarking test comparing NULL with === is faster.
PASSING PARAMETER BY REFERENCE:
This
is considered as one of the most complicated topic for newbies, well,
its simple. when you pass by reference then whatever processing
performed inside function body will affect your variable in its
life-scope. e.g.:
$maritalStatus = "unmarried";
function welcomeToHell(&$status) {
$maritalStatus = "married";
}
echo $maritalStatus; //displays unmarried
welcomeToHell($maritalStatus);
//changes the variable $maritalStatus value in its life-scope i.e outside function
echo $maritalStatus; //displays married, and yes, I used a meaningful function name :D, jokin...
To
pass by reference you use ampersand ‘&’ sign in function parameter
definition. Since php 5.3.0 you should not use & sign in function
call. if used it gives deprecated warning. From PHP 5.4.0 it gives fatal
error. so use it only in paramater definition.
Passing by
reference can get very deep with advanced tasks. I have made loads of
projects and I rarely used PASS BY REFERENCE. However, if you are
looking to study passing by reference deeper then read PHP Manual and check user-comments
TIP:
a variable defined within a function body remains active only within
the body of the function. It has no effect / scope outside function
body, unless passed-by-reference as above.
$name = "Haroon Ahmad";
function myName($name) {
$name = "Umair Ahmad Khan";
}
echo $name; //it displays Haroon Ahmad
So
the same variable name does nothing here, because the $name of
function’s body is a different variable then the same name variable
outside function body.
RETURNING OUTPUT FROM FUNCTION:
In
advanced level programming, you will ‘usually’ return output from a
function rather than ‘displaying’ it within the function body. Because
in modern web programming you have frameworks which handle PRESENTATION
separate than LOGIC / PROCESSING. so you just have to get the output and
then give it to the PRESENTATION code to format it.
You can return all types of PHP DATA TYPES from a function whether a simple string, variable, array and even an object.
You use the KEYWORD “return” to return a value from function.
function fullName($firstName, $secondName) {
return $firstName . " " . $secondName;
}
fullName("Haroon","Ahmad");
It displays “Haroon Ahmad”
VARIABLE FUNCTION NAME:
You can use a variable to call a function e.g.:
$functionName = "add";
$functionName(); // this will call a function by the name add()
$functionName = "subtract";
$functionName(); // this will call a function by the name subtract()
BUT, this can make coding ambigous. So for me, I would avoid such practice unless desparately required.
CALLING A FUNCTION FROM ANOTHER FUNCTION:
You can call a function from the body of another function.
Consider the following code:
function add($one,$two) {
multiply($one + $two, 2);
}
function multiply($result,$multiplyBy) {
echo $result * $multiplyBy;
}
add(2,2); //displays 8
USING RETURNING VALUE OF A FUNCTION AS A PARAMETER OF OTHER:
You can use a returning value of a function to pass as argument for another function call. See the following example:
function add($one,$two) {
return($one + $two);
}
function multiply($result) {
echo $result * 10;
}
multiply(add(2,2)); //displays 40
CALLING A FUNCTION FROM ITS OWN BODY:
Now let me put your brain to test – what is the output of the following code?
function add($one,$two = NULL) {
if ($two !== NULL) {
return add($one);
} else {
return $one + $two;
}
}
echo add(2,2);
…
hmm tricky, isn’t it? you will find such questions in ZCE Exam. its
output is 2. But regardless of the complexity of this example, I wanted
to show you that you can call a function from its own body. Like here
add() is called within its own body.
What is a PHP Built-in Function?
PHP
has many built-in functions. They are already defined to perform
certain tasks. You just need to call them with correct parameters to
perform desired tasks. exit(); is one of them which halts the execution
of your script.
You can read PHP Functions Manual for further details on built-in functions.
implode and is_array built-in functions:
implode() converts an array to a string with a glue value.
is_array() is very hand and you will use it alot. It finds out of the provided variable is an array or not.
In the following, a little complex, example I will use both of them to show you their working.
function fullName($firstName,$lastName = array()) {
return (is_array($lastName)) ? $firstName . ' ' . implode(' ',$lastName) : $fistName;
}
echo fullName("haroon") . "<br />"; //displays Haroon
echo fullName("haroon",array("Ahmad","Khan")); //displays Haroon Ahmad Khan
You can study explode(), another useful built-in function that you will be using a lot in your practical projects.
With
this I guess we have reached to the end of our PHP Functions
Discussion. This will surely give you a basic concept of how PHP handles
functions. In my Object Oriented Programming Tutorial, I will take this
discussion further and will show you some very detailed examples of
Functions. Advance and Practical Programming is all about using
Functions. So practice them as much as you can to clear your all
concepts, read PHP manual and feel free to get back to me with your all
questions and comments.