Tuesday, October 22, 2013

Functions in PHP

In PHP as in any other programming language, programmers often use something called functions or methods to keep our code pretty organized and reuse code when needed.
So basically we can say that a function behaves like a little program, that we can use to reuse code and write less in our programs, for instance, imagine a calculator program, in which the user can make a lot of additions, this would require to use code for making this additions as many times as the user needs, and with a simple function we can reuse the same code. Lets see how we can create these functions.

How to create a function in PHP

To create functions we most declare them, type in a PHP file the following code to see how it’s done.
01<?php
02/*We declare a simple hello world function to print a text
03However code isn't instantly executed, you must call this function later to reuse the code*/
04
05function hello_World()
06{
07  echo "Hello eveyone!!";
08}
09
10/*Now we call the function just by typing it, you can call it as many times as you want*/
11hello_World();
12
13?>

This was an easy way to create a function and use it right?
In the next video I will explain a little bit more about functions in a more visual way.
PHP function’s Video tutorial

How to use parameters in a PHP Function

Now parameters are a better way to use functions, you define parameters inside parenthesis in functions, see the example below in which we can use a function to get the result of the addition of two diferent numbers.
01<?php
02 
03/*Notice in this function 2 different parameters separated by the ',' character, they will be variables and may affect the result of the function*/
04function add_Numbers($number_a,$number_b)
05{
06   $result = $number_a+$number_b; /*We make the addition and store the result in a new variable*/
07   echo $result; /*we print the result on our document */
08}
09 
10/*Now lets call this function...twice*/
11 
12add_Numbers(10,5);
13add_Numbers(7,-11);
14 
15/*Notice how we enter parameters in the function, depending of the parameters we give to the function, the result will be different, because parameters are naturally variable, try saving this php file and run this code to see what happens*/
16 
17?>

That would be all for now, I hope you guys liked this tutorial, please don’t forget to comment below!