Login

PHP Functions

If you’re looking for a way to save time when you program, look no further. Creating functions lets you reuse code that you’ve used before without having to rewrite the whole thing. Keep reading to learn how.

While programming, you’ll discover that you use certain pieces of code over and over, either within a script or in several scripts. Instead of writing that code over and over you can create a function and place those routines in it. This will save you time and make programming easier, especially as websites become more complex. Another advantage of a function is that it executes wherever and whenever you call it, in the same way that print() displays text.

User Defined Functions

The syntax to create a user defined function is:

function function_name(){

//statements here

}

You use the same naming conventions as you do for variables, without the dollar sign. Another rule to remember is to not use spaces when giving a name to a function. Otherwise it will be interpreted as two different words which will result in an error message. Use an underscore instead. Also, as a matter of good coding practice, it is good to give a representative name to a function. For example, set_name() would be a better function name than name1().

There are no limits as to how many statements can be included in the function. A function must include all the required elements, which are:

Function name

Opening and closing parentheses – ()

Opening and closing braces – {}

Statements

The actual formatting of the function itself is not important, as long as the above elements are included. You call the function by its name to execute it.

The above function creates a password with random numbers and letters. The $chars variable contains letters and numbers that are mixed up. The content of that variable is then randomized with the rnd() function and a result is returned in the $thepass variable.

The “return $thepass;” part of the function returns the function result to whatever variable you want it in. Therefore to run this function, all we need to do is:

$password =randpass();

{mospagebreak title=Functions that Take Arguments}

In the last section we created a function that generates random passwords. What if we want a password generator that only displays a password of a certain length? For example, what if we only want three characters, or six or eight? This is where a function that takes arguments becomes necessary. Fortunately for us, in PHP you can create such functions.

The syntax for writing functions that take arguments is as follows:

function function_name($argument){

statements

}

The argument is usually in the form of a variable, but can also be literal, or both:

function function_name($argument,’Avalue’){

statements

}

If you do not add an argument where it is needed, the function will display a error message. The same thing will happen if you only add three arguments when a function expects four. To call a function that takes an argument is the same as calling the ones that don’t take arguments. You just need to remember to pass along the needed arguments.

Let’s modify our randpass() function to enable us to choose how many characters we want in our password.

And this screen shot shows the result for an eight character password.

Shown above is what happens when you don’t pass an argument to the function.

There are no limits to how many arguments a function can take, and you can use multiple functions in a script. You can also create a separate file for all your functions and just include it in your scripts to use the functions.

{mospagebreak title=Setting Default Values}

When creating a function that takes arguments, you can set default values for it:

function function_name($argument2, $argument = 6){

statements

}

Why would you want to set default values in a function? Well, if you are for example writing a program that involves calculating tax, which does not change often but does change sometimes, a function like this would be appropriate. It allows the assumption of a value, but still permits you to change the value when needed.

The default value is overwritten when you specify a value, otherwise the value will stay the same. For example, let’s create a new function that will take your age, first name and last name:

function mydetails($firstname, $lastname, $age=23){

echo “My name is ” .$firstname. ” ” .$lastname. ” and I am
“.$age.” years old.”;

}

To call this function, type: mydetails(34,’John’,’Doe’)

And the result will be…

My name is John Doe and I am 34 years old

As you can see, the default value of 23 has been overwritten to 34.

If, for example, you call this function without the $age argument, the function will assume that $firstname is the first argument. In other words, it will replace $age with $firstname and $firstname with $lastname. In that case, when you call this function, the results will be:

My name is Doe and I am John years old.

Just make sure that you write the default values after the other standard values (the arguments without defaults):

function mydetails($firstname, $lastname, $age=23){

echo “My name is ” .$firstname. ” ” .$lastname. ” and I am
“.$age.” years old.”;

}

This is because PHP assigns the values directly to the arguments as they are received from the call line.

{mospagebreak title=Creating Functions that Return a Value}

In the last section of this article we discuss functions that return a value. In the previous section we already touched on this kind of function. There are only two differences between the previous functions we discussed and functions that return a value. First, you use the return statement within the function. Second, you assign the result to a variable.

The syntax of a function that returns a value is something like this:

function function_name($argument1,$argument2){

statements;

return $value;

}

As with our randpass() function in earlier sections, to call a function that returns a value we do this:

$variable = function_name($argument);

Another example is:

function sayhello($argument){

return “Hello $argument!”

}

A user defined function usually returns just a single value, but it can also return more than one value when arrays are used. Here’s a example of how it’s done:

function fname($arg1,$arg2,$arg3){

//your statements here

return array($value1,$value2,$value3);

}

….and here’s how you’d use the function…..

list($val1,$val2,$val3)=fname($n1,$n2,$n3);

The $value1 from the function is assigned to $val1 and $value2 is assigned to $val2 and so forth.

{mospagebreak title=Using Variables in Functions}

You’ve used functions that take arguments. These arguments are variables that have been passed to the function as arguments when a function is executed. You can also use variables within a function using the global statement.

The global statementextends the scope of a variable. The term scope refers to the realm in which the variable can exist. For example, the scope of a variable that you create in a script exists throughout the life of that script. In other words, the variable can be used anywhere in the script, in the same way that environment variables such as $_SERVER[‘PHP_SELF’] exist throughout the server.

Functions create a new realm for variables to exist in. Function variables such as the arguments passed by a script, and variables defined within a function, exist only within that function and cannot be used outside of the function’s realm. These kind of variables are called “local” variables with a “local” scope. In the same vein, the variables outside a function can only be passed to a function as an argument or by the use of the term “global.”

The “global” statement makes a variable be the same outside and within the function. In effect a local variable with local scope is turned into a global variable with global scope. So, any changes made to this variable within a function are also passed on to the variable when it is used outside of the function.

The syntax of a global variable is:

function function_name($argument){

global $variable;

statements

}

As long as $variable exists outside of the function, it will also have the same value within the function. Here’s a simple demonstration:

<?php$n1 = 2;$n2 = 2;

function Add(){ global $n1, $n2;

$n2 = $n1+ $n2;}

Add();

echo $n2;?>

The above outcome will be “4” because we declared $n2 and $n1 as global within the function, and that caused those “global” variables to reference the variables declared in the script.

Conclusion

Functions make it easy to code when you are working on large projects and also make your code more portable. Another thing to keep in mind about functions in general, is that their execution time is slower than if you’d just written it out. But you would not really notice it, especially if you are not a programmer. This is particularly true if you use classes in larger projects. We will be discussing classes in an upcoming article.