PHP Functions. Here’s What You Need To Know About Functions In PHP

Posted by TotalDC

In the last article we talked about various loops in PHP and how to use them. Now let’s look at functions and everything you need to know about them then you are starting to program in PHP.

PHP Built-in Functions

First of all – function is a self-contained block of code that performs a specific task.

As you may guess PHP has a large collection of built-in functions that you can call directly within your PHP code to perform a specific task, like var_dump(), gettype() and lots more.

User Defined Functions in PHP

But you are not just stuck with built-in functions. In PHP you can define your own functions. It is a way to create reusable code that performs specific tasks and can be maintained separately from main program. Let’s look at some of the 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 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.
  • 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.

Now that that’s out of the way, we can look at how easily you can define your own functions in PHP.

Creating And Invoking Functions

The basic syntax of creating a function looks like this:

function functionName(){
    // Your code goes here
}

You start your function with word function, then write name of your function followed by parentheses () and then simply write your function’s code between curly brackets {}.

This is simple example of an user-defined function:

<?php
// Defining function
function helloWorld(){
    print "Hello World!";
}
// Calling function
helloWorld();
?>

Functions With Parameters

Functions can have parameters that you specify when you create your function.

function yourFunction($parameterOne, $parameterTwo){
    // your code goes here
}

You can define as many parameters as you want. But keep in mind that corresponding argument needs to be passed to the function when you call it.

The getSum() function in following example takes two integer values as arguments, simply add them together and then display the result in the browser.

<?php
// Defining function
function getSum($num1, $num2){
  $sum = $num1 + $num2;
  print "Sum of the two numbers $num1 and $num2 is : $sum";
}
 
// Calling function
getSum(5, 10);
?>

The output of the above code will be:

Sum of the two numbers 5 and 10 is : 15

Functions With Default Values

You can define default values to your function’s parameters. Just insert the parameter name with = sign and specify default value of that parameter.

<?php
// Defining function
function customFont($font, $size=15){
    print "<p style=\"font-family: $font; font-size: {$size}px;\">Hello, world!</p>";
}
 
// Calling function
customFont("Arial", 2);
customFont("Times", 3);
customFont("Courier");
?>

In this example third call to customFont() include second argument. This forces PHP to use default value for the $size parameter if no other value is given in your code.

Returning Values

A function can return value back to the script that called the function using the return statement. You can return any tipe of value, including arrays and objects.

<?php
// Defining function
function getSum($num1, $num2){
    $total = $num1 + $num2;
    return $total;
}
 
// Printing returned value
print getSum(5, 10); // Result: 15
?>

Since function can contain only one return statement, you have to use arrays in order to return multiple values.

<?php
// Defining function
function divideNumbers($dividend, $divisor){
    $result= $numOne / $numTwo;
    $array = array($numOne, $numTwo, $result);
    return $array;
}
 
// Assign variables as if they were an array
list($numOne, $numTwo, $result) = divideNumbers(10, 5);
print $numOne;  // Result: 10
print $numTwo;   // Result: 5
print $result;  // Result: 2
?>

Variable Scope

Although you can declare the variables anywhere in your PHP code, but the location of the declaration determines the extent of a variable’s visibility within the PHP program (where the variable can be accessed). This is known as variable scope.

Variables declared within a {} of a function are local and they can’t be viewed or changed from outside of that function.

<?php
$greet = "Hello World!";
 
// Defining function
function greetUser(){
    print $greet;
}
 
greetUser();  // Generate undefined variable error
 
print $greet; // Result: Hello World!
?>

Global Variable

If you are in a situation where you need to import a variable from the main program into a function or vice versa you can use the global keyword before the variables inside the function. This keyword transforms your simple variable into a global variable, making it visible or accessible outside of the function.

<?php
$greet = "Hello World!";
 
// Defining function
function greetUser(){
    global $greet;
    print $greet;
}
 
greetUser(); // Result: Hello World!
print $greet; // Result: Hello World!
 
// Assign a new value to variable
$greet = "Goodbye";
 
greetUser(); // Result: Goodbye
print $greet; // Result: Goodbye
?>

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: