Writing Your Own Functions – PHP

Functions exist in most programming languages and they separate code that performs a single well-defined task. This makes it easier to read and reuse the code. A function is a self-contained module of code that prescribes a calling interface, performs some task and optionally returns a result.

There are several reasons to write your own functions in PHP; for instance if you want to perform a task that other built-in functions cannot help you do. Let us quickly look at an example of a function call before we do function definition.

[php]
<?php
#call a function in php
function_name();

#this line calls a function named function_name that does not
#require parameters. This line also ignores any possible values
#that might be returned by the function.

#You might have come across phpinfo() function used to test
#php version, information about php, the web server setup etc
#it takes no parameters:
phpinfo();
?>
[/php]

Most functions however do require a parameter or more – which are the inputs to the functions. If a function expects a parameter to be passed, you can either pass in the exact value or a variable containing the value. Let us see an example

[php]
<?php
#this function expects 1 parameter (string):
function_name(‘parameter’);

#this function expects a number:
function_name(2);

#we use a variable as a parameter here
function_name($age);

#Consider fopen() function’s prototype here:
resource fopen(string filename, string mode
[, bool use_include_path [, resource context]]);

#The above prototype tells you several things: resource word tells
#you that the function fopen() returns a resource(an open file
#handle). The function parameters are inside the parentheses:
#filename & mode are both strings and then bool use_include_path
# and lastly
#context which is of type resource!

?>
[/php]

The square brackets around use_include_path and context indicate that these parameters are optional.That means you can choose to provide values for optional parameters or you can ignore them in which case the default values will be used. Note that for functions with more than one optional parameter, you can only leave out parameters from the right. In our example, you can leave out context or both use_include_path and context but you cannot leave out use_include_path and provide context.

Knowing the above prototype therefore makes it easier to understand the code below as valid:

[php]
<?php
$name = ‘myfile.txt’;
$openmode = ‘r’;
$fp = fopen($name, $openmode);

#the above line calls fopen() passing in $name and $openmode
#whatever is returned is stored in $fp variable
?>
[/php]

One common mistake among new php users is calling a function that is not defined. If you do that, you will get an error message! Always check to see if your functions are spelled correctly during definition and check to see if the function exists in the version of PHP you are using.

You might not always remember how the function names are spelled. For instance, some two-word functions have an underscore between the words and some don’t. The function stripslashes() runs the two words together while strip_tags() separates the two words with an underscore.

You will also get an error message if you try to call a function that is part of a PHP extension that is not loaded. It is a good thing to name your functions with lowercase for consistency.

The cool thing about programming languages is the ability to write your own functions. You are not limited to using built-in php functions!

Basic Function Structure in PHP

A function definition starts with the keyword function and then followed by a name, then the parameters required and contains the code to be executed each time this function is called:

[php]
<?php
#define a function
function my_function(){
echo ‘Hello, my function was called’;
}

#we can now call our function as follows:
my_function(); #you can guess the output!

#built-in functions are available to all php scripts but
#your declared functions are only available to the scripts
#in which they were declared. It is a good idea to have a file
#or set of files containing your commonly used functions. You
#can then use require() to make them available to your scripts.
?>
[/php]

Naming Functions In PHP

The main point to consider while naming your functions is; short but descriptive. Consider a page header function – pageheader() or page_header() sound pretty good! There are restrictions to follow:

  • Your function cannot have the same name as an existing function.
  • Your function name can only contain letters, digits and underscores.
  • Your function name cannot begin with a digit.

As opposed to other languages, function overloading – the feature that allows you to reuse function names, in PHP is not supported.

[php]
<?php
//examples of valid function names
name()
name2()
name_three()
_namefour()

//examples of invalid function names
5name()
name-six()
fopen() #this could be valid if it didn’t already exist!

?>
[/php]

Using Parameters In Functions

[php]
<?php
function create_table($data) {
echo “<table border=”1″>”;
reset($data); // Remember this is used to point to the beginning
$value = current($data);
while ($value) {
echo “<tr><td>”.$value.”</td></tr>n”;
$value = next($data);
}
echo “</table>”;
}

#You can call create_table($data) by passing in values like this:
$my_array = array(‘This is Line one’, ‘This is Line two’,
‘This is Line three’, ‘This is Line four’);
create_table($my_array);

?>
[/php]

If you run that simple code, you will get:
functions-testing

Just like built-in functions, your functions can have no parameters, one parameter or more than one parameter. Let us improve our above function to include some optional parameters:

[php]
<?php
#allow the caller to set the border width, cellspacing and
#cellpadding:
function create_table2($data, $border=1,
$cellpadding=4, $cellspacing=4 ) {
echo “<table border=””.$border.””
cellpadding=””.$cellpadding.””
cellspacing=””.$cellspacing.””>”;
reset($data);
$value = current($data);
while ($value) {
echo “<tr><td>”.$value.”</td></tr>n”;
$value = next($data);
}
echo “</table>”;
}

#Now let us call our function passing in the parameters
$my_array = array(‘This is Line one.’,’This is Line two.’,
‘This is Line three’, ‘This is Line four.’);
create_table2($my_array, 3, 8, 8);
?>
[/php]

If we run the above code, we get a much better table because we can adjust the parameter values as we wish. If we don’t supply them, the default values are used! This is what we get on the browser.
better-function

Understanding Scope

A variable scope controls where that variable is visible and usable. Below are the simple rules in PHP to follow:

  1. Variables declared inside a function are in scope from the statement in which they are declared to the closing brace at the end of the function. This is called function scope. These are called local variables.
  2. Variables declared outside functions are in scope from the statement in which they are declared to the end of the file but not inside functions. This is called global scope. These variables are called global variables.
  3. The special superglobal variables are visible both inside and outside functions.
  4. Using require() and include() statements does not affect scope. If the statement is used inside a function, the function scope applies. If it is not inside a function, the global scope applies.
  5. The keyword global can be used to manually specify that a variable defined or used inside a function will have a global scope.
  6. Variables can be manually deleted by calling unset($variable_name) .A variable is no longer in scope if it has been unset.

Example of scoping:

[php]
<?php
#declare a function and a variable inside it
function fn(){
$var = “contents”;
}

#the $var variable declared inside our fn() function has function
#scope.
fn();
#Trying to refer to $var outside our fn() function will create a
#new $var variable with global scope.It will be visible till the
#end of the file. Using $var with just echo will return nothing
#because it has no value at the moment.
echo $var;

#The inverse of the above example:
function fn(){
echo “inside the function, $var = “.$var. “<br />”;
$var = ‘contents 2’;
echo “inside the function, $var = “.$var. “<br />”;
}
$var = ‘contents 1’;
fn();
echo “outside the function, $var = “.$var. “<br />”;

#—————–OUTPUT——————————-#
#inside the function, $var =
#inside the function, $var = contents 2
#outside the function, $var = contents 1

#If you want to create a global variable inside a function,
#you simply use the global keyword (global $my_variable)

?>
[/php]

Pass By Reference vs. Pass by Value
Let us consider a simple function increment()

[php]
<?php
function increment($value, $amount = 1) {
$value = $value +$amount;
}

$value = 10;
increment($value);
echo $value    # 10 – no change

#—————————–Solution————————-#

function increment(&$value, $amount = 1) {
$value = $value +$amount;
}

$a = 10;
echo $a;   #10
increment($a);
echo $a;  #11

#Explanation:
#————-by value ———————–#
#If you pass by value, a new variable is created containing the
#value passed in. It is a copy of the original. Modifying this new
#variable does not change the original value.

#—-by reference—————————–#
#Instead of creating a new variable, the function receives a
#reference to the original variable.This reference has a variable
#name starting with a $ sign and can be used like any other
#variable. Modifying this reference variable affects the original
#variable.
#You specify a pass by reference parameter by using an ampersand(&)
#before the parameter name in the function definition.
?>
[/php]

Using The return keyword:

The keyword return ends the execution of a function. Execution of a function ends either after all statements have been executed or the return keyword is used. Consider this example:

[php]
<?php
function test_return() {
echo “This statement will be executed”;
return;
echo “This statement will never be executed”;
}
#Calling the above function will cause the first echo
#statement to be executed and not the second one!
?>
[/php]

The above example is obviously not the best way to use return keyword. Normally, you want to use it while checking for some conditions being met or not. Let us see a simple example here:

[php]
<?php
function larger( $x, $y ) {
if ((!isset($x)) || (!isset($y))) {
echo “This function requires two numbers.”;
return;
}
if ($x>=$y) {
echo $x.”<br/”>;
} else {
echo $y.”<br/”>;
}
}
#testing the function
$a = 1;
$b = 2.5;
$c = 1.9;
larger($a, $b);
larger($c, $a);
larger($d, $a);
#The output is as follows:
2.5
1.9
This function requires two numbers

?>
[/php]

Returning values from functions
You can simply return values directly from functions as follows:

[php]
<?php
#modified version of larger that use return
#instead of echo to return the value
function larger ($x, $y) {
if ((!isset($x)) || {!isset($y))) {
return false;
} else if ($x>=$y) {
return $x;
} else {
return $y;
}
}
#————–sample test code————–#
$a = 1; $b = 2.5; $c = 1.9;
echo larger($a, $b).’<br />’;
echo larger($c, $a).’<br />’;
echo larger($d, $a).’<br />’;

2.5
1.9
#——————————————–#
?>
[/php]

Implementing Recursion in PHP
Recursion is supported in PHP. A recursive function is a function that calls itself. They are more useful when navigating dynamic data structures such as linked lists and trees. Example:

[php]
<?php
#———-recursive approach————-#
function reverse_r($str) {
if (strlen($str)>0) {
reverse_r(substr($str, 1));
}
echo substr($str, 0, 1);
return;
}

#————iterative approach———–#
function reverse_i($str) {
for ($i=1; $i<=strlen($str); $i++) {
echo substr($str, -$i, 1);
}
return;
}

reverse_r(‘Hello’);
reverse_i(‘Hello’);

#calling reverse_r(‘Hello’) will call itself a number of times,
#with the following parameters:

reverse_r(‘ello’);
reverse_r(‘llo’);
reverse_r(‘lo’);
reverse_r(‘o’);
reverse_r(‘’);

?>
[/php]

The above functions  do the same thing but using recursive and iterative approaches respectively.
With each iterative call in the first function, the length of the string is tested. When you reach the end where strlen($string) == 0, the test fails. One issue with recursion is the memory use. It is up to you to decide which approach fits your taste.

As I end this post, I would like to direct you to PHP documentations where you can find out more. Thanks for stopping by and I hope you found some useful information here. If you have any questions, please let me know through the comments section. If you spot any errors, please let me know as well.

Be The First To Get New Posts From Simple Developer…

Written By Elisha Chirchir

Elisha Chirchir is a software developer. He is also the founder of Simple Developer and co-founder of Instinctive Software Solutions. On any given day, he works on both Android and Web Development. During his 'free time', he offers training to those interested in learning how to code in php, java, python, javaScript etc. You can easily find him on StackOverflow Android chatroom or on Twitter @Eenvincible

2 Comments on “Writing Your Own Functions – PHP

  1. latest indian songs Reply

    July 9, 2014 at 8:23

    Hi, i think that i saw you visited my site so i came to “return the favor”.I’m trying to find things to
    improve my website!I suppose its ok to use some of your ideas!!

    Visit my weblog latest indian songs

    • Elisha Chirchir Reply

      July 12, 2014 at 5:21

      You are welcome to use my ideas. Thanks for stopping by.

Leave a Reply

Your email address will not be published. Required fields are marked *