Learn all about PHP functions: How to create your own functions, how variable scope works, the concepts of references and recursion, and more!
You’re no doubt familiar with using functions in PHP. The language contains thousands of built-in functions that you can use for all sorts of handy jobs — from manipulating text through to reading files, sending email messages and processing images.
You’re not limited to using just the predefined functions, though — you can create your own functions too! Now we will show you how. You’ll learn:
  • Why it’s good to create your own functions
  • How to create and use a function
  • How to make your functions flexible by using parameters
  • All about optional parameters and default values, and
  • How to return values from your functions.
Ready? Let’s get started!

Why make your own functions?

By creating and using your own functions, you get the following advantages:
  • You reduce code duplication.
    If you’re writing a reasonably long PHP script, chances are that you’ll need to do the same thing more than once at different points in the script. By wrapping this common code in a function, you avoid having to write the code more than once.
  • You can reuse code across scripts.
    Once you’ve encapsulated some code inside a function, it’s easy to separate that function out into a library file. You can then use the function from within many different scripts.
  • You can write complex code more easily.
    It’s easier to write a large application if you split it into many smaller functions, because you only have to think about how to write one simple function at a time.
  • You can reduce errors in your code.
    Rather than having to track down and eliminate the same error in, say, 10 similar blocks of code throughout your application, you only have to isolate and fix the problem in a single function.

How to create a function

OK, so making your own functions is cool. How do you do it?
Here’s the basic idea:
function myFunctionName() {
// (Your function code goes here)
}
Pretty easy, eh! Here’s an example that shows how to create, then use, a function:
<?php

function helloWorld() {
echo "Hello, world!";
}

// Displays: "Hello, world!"
helloWorld();
?>

As you can see, you use, or call, a function you’ve created yourself in exactly the same way as you call a built-in PHP function. You write the function name, followed by ().
When the PHP engine encounters your function call, it passes control to the function and runs the code inside it. When the function’s code has finished, control is returned to the point after your function call.

Defining and using parameters

Great! Now you know how to create your own functions, and how to call a function you’ve created from elsewhere in your code. Remember that functions are reusable — you can call the same function from many different points in your code.
Reusable functions are great, but in order to make them even more useful and flexible, you can useparameters and arguments:
  • Parameters are special variables that you set up when you create your function. These variables can accept values from the code that calls the function. The code inside your function can then work with those values.
  • Arguments are those values that you pass to the function when you call it.
This means that your functions can do different things based on the values that you give them, making them much more flexible.
To define parameters in a function, you specify the parameter names inside the parentheses when you create the function:
function myFunctionName( parameter1, parameter2, ... ) {
  // (Your function code goes here)
}

To pass values to your function when you call it, you again put them inside the parentheses:
myFunctionName( argument1, argument2, ... )

Here’s an example to make this crystal clear:
<?php

function sayHelloTo( $firstName, $lastName ) {
echo "Hello, $firstName $lastName!<br>";
}

// Displays: "Hello, John Smith!"
sayHelloTo( "John", "Smith" );

// Displays: "Hello, Mary White!"
sayHelloTo( "Mary", "White" );

?>
Here’s how the above code works:
  1. First we create a function called sayHelloTo() that has 2 parameters, $firstName and $lastName. The function code displays these 2 values using echo.
  2. We then call the function, passing in the values "John" and "Smith". The value "John" is transferred to the $firstName parameter, and "Smith" is transferred to $lastName. The end result is that the function displays “Hello, John Smith!”.
  3. We then call the function again with different arguments, producing a different result: “Hello, Mary White!”.
So by adding parameters to our sayHelloTo() function, we’ve made the function much more flexible. It can now say hi to anybody!

Creating optional parameters

Sometimes it’s useful to make parameters optional. When you make a parameter optional, you also give it a default value. If the calling code doesn’t pass a value for that parameter, the default value is used instead.
Here’s how to define an optional parameter:
function myFunctionName( parameterName=defaultValue ) {
  // (Your function code goes here)
}
Let’s make an example that uses optional parameters. We’ll take the sayHelloTo() function we wrote earlier, and add an optional parameter for a custom greeting. If the calling code doesn’t pass a value for the parameter, we’ll default to “Hello”:
<?php

function sayHelloTo( $firstName, $lastName, $greeting="Hello" ) {
echo "$greeting, $firstName $lastName!<br>";
}

// Displays: "Hello, John Smith!"
sayHelloTo( "John", "Smith" );

// Displays: "Howdy, Mary White!"
sayHelloTo( "Mary", "White", "Howdy" );

?>
As you can see, we’ve defined our function with an optional parameter and default value. We then call the function twice. The first time, we don’t pass a value for the $greeting parameter, so the function defaults to “Hello”. The second time, we pass the value “Howdy” for the $greeting parameter, so “Howdy” is used instead of the default.

Returning values from your functions

To make your functions even more versatile, you can get them to return values back to your calling code. This means your calling code can have a 2-way conversation with your function: When it calls the function it can pass the function some values, and it can also receive a reply from the function when the function ends.

Note: Both parameters and return values are optional. A function can have parameters or return a value, or it can do both, or neither.
To return a value from a function, you use the return keyword, as follows:
function myFunctionName() {
  // (Your function code goes here)
  return value;
}

When you then call the function, the function call takes on the returned value. For example, you can read the returned value in your calling code like this:
$returnValue = myFunctionName();

Let’s rewrite our sayHelloTo() function above to return the greeting string, instead of displaying it. We can then display it from within our calling code:
<?php

function sayHelloTo( $firstName, $lastName, $greeting="Hello" ) {
return "$greeting, $firstName $lastName!<br>";
}

// Displays: "Hello, John Smith!"
echo sayHelloTo( "John", "Smith" );

// Displays: "Howdy, Mary White!"
echo sayHelloTo( "Mary", "White", "Howdy" );

?>

PHP Variable Scope

Discover how variable scope works in PHP. This beginner tutorial explores global and local scope, and shows how to access globals within functions, work with superglobals, and create static variables.
When you’re just starting to work with functions and objects in PHP, variable scope can be the cause of some confusion. Fortunately, PHP’s scope rules are relatively easy to understand (compared to some other languages, at least!).
In this tutorial you’ll learn all you need to know about variable scope in PHP. You’ll look at:
  • The concept of variable scope — what it is, and what it means
  • The differences between global and local scope
  • How to access global variables from within a function
  • PHP’s superglobals, and how they work
  • How to use static variables to preserve state
Let’s get started!

What is variable scope, anyway?

The scope of a variable in PHP is the context in which the variable was created, and in which it can be accessed. Essentially, PHP has 2 scopes:
Global
The variable is accessible from anywhere in the script
Local
The variable is only accessible from within the function (or method) that created it
Variable scope — and, in particular, local scope — make your code easier to manage. If all your variables are global, they can be read and changed from anywhere in your script. This can cause choose in large scripts as many different parts of the script attempt to work with the same variable. By restricting a variable to local scope, you limit the amount of code that can access that variable, making your code more robust, more modular, and easier to debug.
Here’s a simple example that shows how global and local variables work:
<?php

$globalName = "Zoe";

function sayHello() {
$localName = "Harry";
echo "Hello, $localName!<br>";
}

sayHello();
echo "The value of \$globalName is: '$globalName'<br>";
echo "The value of \$localName is: '$localName'<br>";

?>

This script displays the following:

Hello, Harry!
The value of $globalName is: 'Zoe'
The value of $localName is: ''

In this script, we create 2 variables:
  • $globalName is a global variable since it’s not created inside any function.
  • $localName is a local variable, created and used inside the function sayHello().
After creating the global variable and the function, the script calls sayHello(), which displays
‘Hello, Harry!’. The script then attempts to display the values of the 2 variables by using echo. Here’s what happens:
  • Since $globalNamewas created outside the function, it is accessible from anywhere in the script — including this point — so its value, ‘Zoe’, is displayed.
  • $localName, on the other hand, is only accessible from within the sayHello() function. Since the echostatement is outside the function, PHP won’t let the code access this local variable. Instead, PHP assumes that the code wants to create a new global variable called $localName, which it sets to the default value of an empty string. This is why the second call to echo displays the value of$localNameas .

Accessing global variables from within functions

As I mentioned above, you can read and change a global variable’s value from anywhere in your script.
To access a global variable from outside a function, just write the variable’s name. To access a global variable from within a function, however, you first need to declare the variable as global within the function by using the global keyword:
function myFunction() {
  global $globalVariable;
  // Access the variable as $globalVariable
}
If you don’t do this then PHP assumes you’re trying to create or use a local variable.
Here’s an example script with a function that accesses a global variable:
<?php

$globalName = "Zoe";

function sayHello() {
$localName = "Harry";
echo "Hello, $localName!<br>";

global $globalName;
echo "Hello, $globalName!<br>";
}

sayHello();

?>
This script produces the following output:
Hello, Harry!
Hello, Zoe!
The sayHello() function uses the global keyword to declare the $globalNamevariable as global. It can then access the variable and display its contents (
‘Zoe’).

Static variables: Variables that like to stick around

When you create a local variable inside a function, that variable only hangs around while the function is being run. As soon as the function exits, the local variable vanishes. When the function is called again, a new local variable is created.
Mostly this is a good thing. It ensures that your functions are self-contained, and that they work the same way each time they’re called.
However, there are situations where it’s handy to create a local variable that remembers its value between one call to the function and the next call. This is exactly how static variables work.
To create a static variable in a function, you write the keyword static followed by the variable name, and give the variable an initial value. For example:
function myFunction() {
  static $myVariable = 0;
}
Let’s look at a situation where static variables are useful. Say you’ve written a function that creates widgets, and returns the number of widgets created so far. You might try doing this using a local variable:
<?php

function createWidget() {
$numWidgets = 0;
return ++$numWidgets;
}

echo "Creating some widgets...<br>";
echo createWidget() . " created so far.<br>";
echo createWidget() . " created so far.<br>";
echo createWidget() . " created so far.<br>";

?>
However, since $numWidgets is recreated each time the function is called, it doesn’t produce the desired result:
Creating some widgets...
1 created so far.
1 created so far.
1 created so far.
By making the variable static, we can get it to stick around from one function call to the next, preserving its value:
<code><?php

function createWidget() {
static $numWidgets = 0;
return ++$numWidgets;
}

echo "Creating some widgets...<br>";
echo createWidget() . " created so far.<br>";
echo createWidget() . " created so far.<br>";
echo createWidget() . " created so far.<br>";

?>
The script now displays the expected output:
Creating some widgets...
1 created so far.
2 created so far.
3 created so far.
Note: While static variables remember their values across function calls, they only last as long as the running script. Once the script exits, a static variable gets destroyed, just like local and global variables do.

PHP Recursive Functions: How to write them, and why they’re Useful

Like most programming languages that support functions, PHP lets you write recursive functions. In this tutorial, we’ll explore the concept of recursion in PHP, and discover how to create recursive functions for various tasks.
Recursion is one of those topics that can seem confusing at first, but once you start writing recursive functions you’ll see how elegant recursion can be!

What is recursion?

Broadly speaking, recursion occurs when something contains, or uses, a similar version of itself. That similar version then contains or uses another similar version of itself, and so on. Sometimes this process can go on forever, such as when you hold 2 mirrors directly opposite each other, creating an infinite series of reflections. More often, though, the number of repetitions, or “depth” of the recursion, is limited by some sort of end condition.
Recursion occurs in all sorts of everyday situations. For example, many artists have created recursive pictures, where the picture contains a smaller version of itself; that smaller version then contains another smaller version, and so on. A famous example of this is the picture on the Droste cocoa tin:

Recursion in computing

When talking specifically about computer programming, recursion occurs when a function calls itself. There’s nearly always an end condition of some sort — known as the base case — otherwise the function would continue to call itself indefinitely (or at least until the computer ran out of memory).
Recursion can be thought of as an alternative to iteration — that is, while and for loops. Some problems are better suited to recursion, while others are easier to do with iteration. Often you can use either recursion or iteration to solve a particular problem.

How to write a recursive function in PHP

In general terms, a recursive function works like this:
  1. The calling code calls the recursive function.
  2. The function does any processing or calculations required.
  3. If the base case has not yet been reached, the function calls itself to continue the recursion. This creates a new instance of the function.
  4. If the base case is reached, the function just returns control to the code that called it, thereby ending the recursion.
In pseudocode, a simple recursive function looks something like this:
function myRecursiveFunction() {
  // (do the required processing...)
  if ( baseCaseReached ) {
    // end the recursion
    return;
  } else {
    // continue the recursion
    myRecursiveFunction();
}
The best way to understand recursive functions is to look at some practical examples. Let’s explore 2 complete PHP examples that show how recursion works:
  1. Factorials, and
  2. Reading a tree of files and folders

Example 1: Factorials

If you remember your high school maths, a factorial of a given number is the product of all positive integers between 1 and the number (inclusive). For example:
5! = 5 x 4 x 3 x 2 x 1 = 120
Let’s write a recursive function to calculate the factorial for a given number, n:
<?php
// recursive function
// to calculate factorial
function calcFactorial($num) {
// define variable to hold product
static $product = 1;
// recurse until $num becomes 1
if ($num > 1) {
$product = $product * $num;
$num--;
calcFactorial($num);
}
return $product;
}
// result: "Factorial of 5 is 120"
echo "Factorial of 5 is " . calcFactorial(5);
?>
Comments
PHP supports recursive functions, which are essentially functions that call themselves repeatedly until a particular condition is met. Recursive functions are commonly used to process nested data collections—for example, multidimensional arrays, nested file collections, XML trees, and so on. The previous listing illustrates
a simple example of recursion—a function that calculates the factorial of a number by repeatedly calling itself with the number, reducing it by 1 on each invocation. Recursion stops only once the number becomes equal to 1.

PHP References: How They Work, and When to Use Them

References are a very useful part of PHP and, for that matter, most other programming languages. However, references can be somewhat confusing when you first start learning about them.
This tutorial is a gentle introduction to references in PHP. You find out what references are, and how they work. You learn how to create and delete references, as well as pass references to and from functions. You also explore some other uses of references, and discover situations where PHP creates references automatically on your behalf.

What exactly is a reference, anyway?

reference is simply a way to refer to the contents of a variable using a different name. In many ways, references are like file shortcuts in Windows, file aliases in Mac OS X, and symbolic links in Linux.

Assigning by reference

An easy way to create a reference is known as assigning by reference. Consider the following simple example:
<?php

$myVar = "Hi there";
$anotherVar = $myVar;
$anotherVar = "See you later";
echo $myVar; // Displays "Hi there"
echo $anotherVar; // Displays "See you later"

?>
Here we’ve created a variable, $myVar, and given it a value of “Hi there”. Then we’ve assigned that value to another variable, $anotherVar. This copies the value from the first variable to the second.
We then changed the value stored in $anotherVar to “See you later”. Since the 2 variables are independent,$myVar still keeps its original value (“Hi there”), which we then display in the page. So far, so good.
Now, let’s change the above example to assign $myVar to $anotherVar by reference, rather than by value. To do this, we simply put an ampersand (&) after the equals sign
$myVar = "Hi there";
$anotherVar =& $myVar;
$anotherVar = "See you later";
echo $myVar; // Displays "See you later"
echo $anotherVar; // Displays "See you later

Now you can see that $myVar‘s value has also changed to “See you later”! What’s going on here?
Rather than assigning the value of $myVar to $anotherVar — which simply creates 2 independent copies of the same value — we’ve made $anotherVar a reference to the value that $myVar refers to. In other words,$myVar and $anotherVar now both point to the same value. So when we assign a new value to $anotherVar, the value of $myVar also changes.
Note that we could have changed the value of $myVar to “See you later” instead of changing $anotherVar, and the result would have been exactly the same. The 2 variables are, in effect, identical.

Removing a reference

You delete a reference using the unset() function, in the same way that you delete a regular variable.
When you unset a reference, you’re merely removing that reference, not the value that it references:
$myVar = "Hi there";
$anotherVar =& $myVar;
$anotherVar = "See you later";
unset( $anotherVar );
echo $myVar; // Displays "See you later"
The value remains in memory until you unset all references to it, including the original variable:
$myVar = "Hi there";
$anotherVar =& $myVar;
$anotherVar = "See you later";
unset( $anotherVar );
unset( $myVar );
echo $myVar; // Displays ""
$myVar = "Hi there";
$anotherVar =& $myVar;
$anotherVar = "See you later";
unset( $anotherVar );
unset( $myVar );
echo $myVar; // Displays ""

Passing references to functions

References really come into their own when you start passing them as arguments to functions. Normally, when you pass a variable to a function, the function receives a copy of that variable’s value. By passing areference to a variable, however, the function can refer to — and, more importantly, modify — the original variable.
To pass an argument by reference, you place an ampersand before the parameter name when you define the function:
function myFunc( &$myParam ) {
  // Do something with $myParam
}
Now, whenever you call myFunc() and pass a variable to it, PHP passes a reference to the variable, rather than the variable’s value.
Let’s look at a simple example of passing by reference:
function goodbye( &$greeting ) {
$greeting = "See you later";
}

$myVar = "Hi there";
goodbye( $myVar );
echo $myVar; // Displays "See you later"
Here we created a function, goodbye(), that accepts a reference to a variable. The reference is stored in the parameter $greeting. The function assigns a new value (“See you later”) to $greeting, which changes the value stored in the variable that was passed to the function.
We test this out by creating a variable, $myVar, with an initial value of “Hi there”, and calling goodbye(), passing $myVar by reference. goodbye() then changes the value stored in $myVar to “See you later”.
So, use pass-by-reference whenever you want a function to change a variable that’s passed to it. Simple!
By the way, don’t be tempted to put an ampersand before the argument name in your function call:
goodbye( &$myVar );  // Don't do this!
The ampersand before the parameter in the function definition is sufficient to pass the variable by reference.
Another Example:
<?php
function goodbye(&$num){
$num=$num*2;
}
$myVar=5;
goodbye($myVar);
echo $myVar; // Display 10
?>
Note: Many built-in PHP functions use pass-by-reference. For example, the sort() function accepts a reference to the array to sort, so that it can change the order of the elements in the array.

Returning references from functions

As well as passing references to functions, you can return references from functions. To do this, place an ampersand before the function name when you define the function. You should also use assign-by-reference (=&) when assigning the returned reference to a variable, otherwise you’ll merely assign the value, not the reference. Here’s an example:
$numWidgets = 10;

function &getNumWidgets() {
global $numWidgets;
return $numWidgets;
}

$numWidgetsRef =& getNumWidgets();
$numWidgetsRef--;
echo "\$numWidgets = $numWidgets<br>";  // Displays "9"
echo "\$numWidgetsRef = $numWidgetsRef<br>";  // Displays "9"

In this example, our getNumWidgets() function retrieves the global variable $numWidgets and returns a reference to it. We then call getNumWidgets(), store the returned reference in $numWidgetsRef, and decrement the value that $numWidgetsRef points to. This is the same value that is pointed to by $numWidgets, as you can see by the results of the echo statements.
You probably won’t use return-by-reference as often as pass-by-reference, but it can be useful in certain situations, such as when you want to write a finder function (or class method) that finds a variable (or class property) and returns a reference to the variable or property, so that the calling code can then manipulate the variable or property.
Using references to change values in foreach loops
Another handy use of references is to change values in an array when using a foreach loop. With a regularforeach loop, you’re working with copies of the array values, so if you change a value you’re not affecting the original array. For example, let’s try to change an array of band names to uppercase with a foreachloop:
<?php

$bands = array( "The Who", "The Beatles", "The Rolling Stones" );

foreach ( $bands as $band ) {
$band = strtoupper( $band );
}

echo "<pre>";
print_r( $bands );
echo "</pre>";

?>
The above example displays:
Array
(
    [0] => The Who
    [1] => The Beatles
    [2] => The Rolling Stones
)
As you can see, the original array has not been changed by the foreach loop. However, if we place an ampersand before $band in the foreach statement then $band becomes a reference to the original array element, rather than a copy. We can then convert the array elements to uppercase:
<?php

$bands = array( "The Who", "The Beatles", "The Rolling Stones" );

foreach ( $bands as &$band ) {
$band = strtoupper( $band );
}

echo "<pre>";
print_r( $bands );
echo "</pre>";

?>
Our code now runs as intended, producing this:
Array
(
    [0] => THE WHO
    [1] => THE BEATLES
    [2] => THE ROLLING STONES
)
Note: Another way to change array values in a loop is to use a for loop instead of foreach.

When references are used automatically

So far you’ve looked at 4 ways to create references explicitly:
  • Assigning by reference
  • Passing by reference
  • Returning by reference
  • Creating a reference in a foreach loop
In addition, there are occasions when PHP automatically creates references for you. Most of the time you won’t care, but it can be useful to know this stuff!

WHEN USING THE GLOBAL KEYWORD

When you use global to access a global variable within a function, you are in fact creating a reference to the global variable in the $GLOBALS array. So:
function myFunction() {
  global $globalVariable;
}
Does the same thing as:
function myFunction() {
  $globalVariable =& $GLOBALS["globalVariable"];
}

WHEN USING $THIS

When you use the $this keyword within an object’s method to refer to the object, then it’s worth remembering that $this is always a reference to the object, rather than a copy of it. For example:
class MyClass {

var $aProperty = 123;

function aMethod() {
$this->aProperty = 456; // $this is a reference to the object
}
}

$myObject = new MyClass();
$myObject->aMethod();
echo $myObject->aProperty; // Displays "456"
Since $this is a reference to the object in the above example, the method is able to change a property within the object to a new value.

WHEN PASSING OBJECTS AROUND

Unlike other types of variable, whenever you assign, pass, or return an object, you’re passing a reference to the object, not a copy. This is usually what you want to happen, since the function or method you pass an object to usually needs to work on the actual object, not a copy of it. For example:
class MyClass {
  // (Class definition here)
}

$myObject = new MyClass();
$yourObject = $myObject;  // $yourObject and $myObject point to the same object
In the few situations when you do actually want to make a copy of an object, you can use the clonekeyword.
Note: In fact, things are a bit more subtle than this. When you create an object variable, that variable merely contains a pointer to the object in memory, not the object itself. When you assign or pass that variable, you do in fact create a copy of the variable. But the copy is also merely a pointer to the object — both copies still point to the same object. Therefore, for most intents and purposes, you’ve created a reference.

class MyClass {
  // (Class definition here)
}
$myObject = new MyClass();
$yourObject = $myObject;  // $yourObject and $myObject point to the same object

0 comments:

Post a Comment

 
Top
Blogger Template