Creating custom functions

As programmers, we often find that we’re performing the same logic at different times in a number of different places. So, to simplify our code PHP lets us define our own custom functions.

A function is a short-hand way of telling PHP to perform a series of steps we’ve defined in advance. A function can accept 0, 1, or multiple arguments as input, and can optionally return one value as output. Of course, if you need to return multiple values, you can bundle them together in an array and return the array.

Here’s the basic syntax:

function someFunctionName($arg1, $arg2, $arg3) {
//some logic
}

Unlike variables, our custom functions can be declared lower down in the execution path than where they actually get called. But this is true only if the function is guaranteed to be defined. If you place your function declaration inside any sort of conditional logic branch, its definition must be processed higher up in the code than any calls to it.

Another thing to notice, your function name must be unique, and it is not case sensitive. So if we have a function like SomeFunctionName somewhere else, then declaring ours is going to cause a fatal error. Not only can you not name your own functions the same, but you can’t use the names of any of the PHP library of built-in functions.

Back to the example though, let’s add some logic so our function does something:

function someFunctionName($arg1, $arg2, $arg3) {
$sum = $arg1 + $arg2 + $arg3;
return $sum;
}

To call it, I just write:

$result = someFunctionName(3,4,5);
echo ‘return value is ‘ . $result;

{show output}

What happens here is that my function call includes the values 3, 4, and 5. And when my function gets run, 3 will be used for $arg1, 4 will be used as $arg2, and 5 will be used as $arg3. It adds them together and returns their sum to the statement that called it, where it gets assigned to the variable $result. However, those variables only have meaning within our function. If we try to use one of them outside the function, PHP treats it like a completely separate variable.

{below call to someFunctionName add: echo ‘$arg1 is ‘ . $arg1;}

{show output}

In addition to a type and a value, PHP variables also have what’s called a scope. It’s sort of like their jurisdiction, to use a law enforcement analogy. Within their scope, they have a value, but outside of it, they have no identity. Once you define a function, all the variables used in there, whether from the argument list or ones you declare inside the logic of the function itself, they are completely isolated from the rest of your script. We refer to them as being in the function’s local scope. You can declare variables with the same names outside the function, but they will be totally different, because variables in the main script are said to be in the global scope. And the value of a variable in the global scope will have no bearing on the value of a variable within a function’s local scope. And the variables in the local scope of one function will be completely independent of the variables in the local scope of another function. However, there are ways around this, and they’re the subject of another video.

Anyway, that’s why functions will often have an argument list – so they can get data from the script to perform their logic on, since they can’t access outside variables directly.¬†And you can see that in this case, the function returned the value 12, since that’s the sum of 3, 4, and 5.

And by the way, as you may have guessed already, calling the function, just like with picking a unique name for it, is not case sensitive. For readability, it is strongly recommended that you always call it with the same case characters for the name, but PHP does not enforce this.

{change function name without changing call}

{show output}

Now, my function definition specifies that it should receive 3 arguments. But watch what happens if I try calling this function with only 2 arguments:

{modify code}

{show output}

Since I defined my function as taking 3 arguments, when I only passed 2 I got that warning. It can keep going, but PHP is telling us that there’s a problem with this. One way to get around that warning is with a special operator in PHP, the @ symbol. If I place it on the line that will trigger a warning, the warning is suppressed. But if we really want to make an argument optional, there’s a better way to do that, and that’s by altering the argument list itself, so that PHP knows an argument is optional.

function someFunctionName($arg1, $arg2, $arg3 = 0) {

When PHP looks at this, it sees that if we omit the 3rd argument, it can still execute the function successfully because it knows that it can just use 3 as a default value in its place.

{show output}

Default values can be any of the simple types, like ints, floats, strings, and booleans, or they can also be arrays or nulls. What you cannot use for your defaults are variables. However, you can use constants, and we’ll look at that more in another video.

As a rule, you should only place your default arguments in the right-hand side of any argument list. Otherwise, any default value to the left of a required value will never get used. If I made my first argument required, I’d still have to pass something for the first argument in order to enter the second and third arguments, assuming they were required. And whatever I passed, even if it was just a null, would always take precedence over the default, so the default would never actually be used.

Now, we’ve seen what happens when we call one of our functions with too few arguments, but what if we call it with too many?

$sum = someFunctionName(3,4,5,6);

{show output}

Notice, nothing changed. PHP doesn’t care if your script passes more arguments than a function says it needs, it only complains if you pass fewer. You can pass a whole slew of arguments to a function that doesn’t have any in its definition. And if you want to see all the arguments that were passed, PHP provides a special set of built-in functions that you can use to do this.

Let’s modify our function a little bit:

function someFunctionName($arg1, $arg2, $arg3) {
if(func_num_args() > 3) {
$sum = array_sum(func_get_args());
} else {
$sum = $arg1 + $arg2 + $arg3;
}
return $sum;
}

Now, don’t get overwhelmed, I realize I’ve just introduced you to 3 new functions here, as well as another way to use functions. The first thing I want to point out is the fact that I’m using the return value of 2 of these functions directly without first casting their return values to a variable. When used this way, we refer to this technique as indirect referencing. PHP supports it just fine. It’s very handy.

As for the PHP built-in functions we’re using, the first one is func_num_args. When called from inside of a function, all it does is return the number of arguments that the function was called with.

The second built-in PHP function, func_get_args, when used inside a function it returns an array containing all of the arguments that were passed to this function.

The last built-in PHP function is one of several we look at together in a later video. Basically, it takes an array, tries to treat all of its values as numbers, and returns their sum total.

So basically, all I’m doing with this revised logic is saying that if our function gets called with more than 3 arguments, just add them all together instead of only adding together the first 3. So, now let’s see how this changes our output:

{show output}

So, obviously the 4th value is now included in that total. And in fact, we can go back and really simplify this function if we want to:

function someFunctionName($arg1, $arg2, $arg3) {
return array_sum(func_get_args());
}

By the way, before I close the video, I didn’t show an example of it, but functions do not need to return a value. That’s entirely optional. Some functions will just print out a fragment of an HTML page, and that’s totally fine. Others might do some specific action like write something to a file or alter some record in a database. There are lots of useful things functions can do without returning anything.

Now that you’ve learned about functions, you’re well on your way to creating some really useful and re-usable code.

February 12 2010 01:24 am | Basics and PHP Programming Basics and PHP tutorial scripts

Trackback URI | Comments RSS

Leave a Reply