What are Functions in PHP

Thanks For Sharing! :-)Share on Google+Tweet about this on TwitterShare on FacebookShare on RedditBuffer this page

What are Functions in PHP

It’s good to encapsulate code you need to run over and over again inside of a function so you don’t have to type it out over and over. Code resuse and keeping it DRY (Don’t Repeat Yourself) is key to providing a maintainable application. A function is simply a piece of PHP code that you can call and it may or may not have parameters that you can send to it, and it also may or may not return a value. We like to give descriptive names to our functions so that we can infer what action they may provide us. Functions are the movers and shakers in PHP, they are the main piece of getting your software to actually do something. In this post we’ll take a closer look at User Defined Functions , Arguments to Functions , Returning Values from a Function, Recursive Functions, as well as Variable Functions. We have a lot to cover so let’s jump right in!


User Defined Functions

PHP has loads of built in functions and sometimes it seems overwhelming where to even begin. Thankfully we already covered the most used php string functions as well as the most used php array functions. Reading up on those will get you going with the key built in functions of the language. Right now we’re going to talk about making our very own functions for our special case use.

The syntax for creating a function is very easy. Let’s check it out:

The naming of the function is any string beginning with a letter or underscore followed by a combination of digits, letters, or underscores. Make it easy on yourself and choose simple descriptive naming for your functions, no need to get fancy. PHP functions are not case sensitive however it is best practice to always use all lowercase letters. Though they don’t have to, functions will usually return a value. This is done using the keyword return, and any number of return statements can be used in the function in condition checking scenarios. Once the return keyword is reached in the program, control goes back to the calling code along with the value produced by the expression in the function. For example:


Arguments to Functions

Functions can accept a certain number of arguments by declaring them in the function definition. There are two different ways to pass parameters to a function and we’ll take a look at them now.

Passing by value

Usually parameters are passed by value in PHP, but you also have the option of passing by reference. The argument in the function is any valid expression which when evaluated assigns the value to the variable in the function.

In the doublefail function, we use pass by value, so when the function runs, it doubles the copy of the variable, not the value of the caller’s variable like the doubleit function does. You could get what you want out of doublefail if you return the copy like in the last example.

Passing by Reference

You can override the scoping rules and have the function gain direct access to a variable by using pass by reference. To do this, you add an ampersand & to the front of the variable name in the parameter list.

The doubleit function passes $value by reference, that is to say the actual value of $b instead of a copy of said value. This allows the function to modify the value directly and when we then echo out the value, we see it gets doubled from 4 to 8 successfully. Only variables can be supplied to parameters declared as passing by reference.

Variable Length Argument Lists

A function may need a variable number of arguments. To declare a function with a variable number of arguments, you leave out the parameter block entirely like this:

PHP gives you three functions to use in the function in order to get the parameters passed to it.

func_get_args() returns an array of all parameters provided to a function;
func_num_args() returns the number of parameters provided to a function;
func_get_arg() returns a specific argument from the parameter list.

For example:

In the following example, the add_arguments_lis() function takes in any number of arguments. It then loops over those arguments, adds to the total on each iteration, and returns the sum of all the values once complete. If no parameters are given, it will simply return false.

These functions cannot be directly used as a parameter to another function. You must first set a variable to the result of the function, and then use that in the function call.


Returning Values from a Function

PHP functions return only a single value with the return keyword:

If you would like to return multiple values, we need to return an array:

or return an object:

If no return value is provided by a function, the function returns NULL.


Recursive Functions

A recursive function is a function that calls itself. Recursion sounds straightforward, but once you start working with it and try to really understand how it works, it can be very tricky.
To write a recursive function, you need to provide it with some means of return or else it will keep calling itself until the program crashes. This is known as the base case. The base case is often found in a conditional like an if statement that will stop the recursion once a condition is met. You also need a recursive case. This is where the recursion, or looping if you will, takes place. The function is called on itself using the recursive case.

Factorials

The textbook example of recursion is the factorial example. The factorial function symbol(!) means to multiply a series of descending non negative numbers like so:

4! = 4 × 3 × 2 × 1 = 24
7! = 7 × 6 × 5 × 4 × 3 × 2 × 1 = 5040
8! = 8 x 7 × 6 × 5 × 4 × 3 × 2 × 1 = 40320

Instead of manually doing this math, we could create a function that accepts a number, and then calculates the factorial by recursion:

Many tutorials leave out the fact that this comes from the formula n! = n × (n-1)! which means “the factorial of any number is that number times the factorial of (1 smaller than that number)

We’ll go step by step through this function using the number 4 to keep it manageable. To do this I have put the code above into eclipse pdt and will step into each execution step.

1. The function definition gets read into memory
2. factorial(4); is called.
3. $number is now 4 so we move to the else clause
4. Recursion! The function calls itself passing in 3 as it’s parameter
5. $number is now 3 so we move to the else clause
6. Recursion! The function calls itself passing in 2 as it’s parameter
7. $number is now 2 so we move to the else clause
8. Recursion! The function calls itself passing in 1 as it’s parameter
9. $number is now 1 so we return 1
10. echo factorial(4); now outputs the answer of 24.


Variable Functions

Variable functions will be useful when we cover object oriented programming. In the mean time we’ll look at the basics of how variable functions work. A variable function is simply where you assign a function name to a variable and then you can call that function by using the variable name.

Let’s remember our example of the factorial function. We could create a random variable name and assign that function to it using the following syntax:

Note that language constructs such as echo() and isset() cannot be called through variable functions:

Now that we have a good grip on functions in PHP, let’s whip up some PHP String Helper Functions to help with common string manipulation tasks!

Thank you for reading What are Functions in PHP – If you found this post helpful, Please do share using the buttons below!

Thanks For Sharing! :-)Share on Google+Tweet about this on TwitterShare on FacebookShare on RedditBuffer this page