Broad Network


PHP Reference

Basics of PHP – Part 14

Forward: In this article I give you the basics of reference in PHP.

By: Chrysanthus Date Published: 29 Jul 2012

Introduction

This is part 14 of my series, Basics of PHP. In PHP references are a means to access the same variable content (value) with different names. Values (variable content) are kept in memory locations. A variable identifies a memory location. A reference is generally used when you are more interested in what is in a memory location and not the variable. PHP reference is different from reference in other computer languages. As you read this article, avoid making comparison with what you read or what exists in other computer languages, like C, as that may confuse you. I have done my best to put this in a logical progressive manner, so take things as I give you.

Note: If you cannot see the code or if you think anything is missing (broken link, image absent), just contact me at forchatrans@yahoo.com. That is, contact me for the slightest problem you have about what you are reading.

Memory Location
A memory location is an area in computer memory that holds the value of a variable.

A Technique to work with one Memory Location
Consider the following statement:

    $var = 5;

The value 5 is in a memory location. You can use this same memory location to increase the value of 5 to 8, by adding 3. You would do this:

     $var = $var + 3;

What happens is this: The computer knows that $var identifies the memory location that has the number 5. For the right operand of the above statement, the computer goes to the memory location identified by $var and adds 3 to what is there. What is there is 5. When 3 is added, you have 8 in the memory location identified by $var. The location having 8, which was assigned to the variable $var, is still assigned to the same variable. Along the line, nothing changed the assignment.

The same principle is applied to strings, as in the following example:

    $var = "one";
    $var = $var . " two";

Notice here that in the second statement, there is a dot between $var and " two". This is called the dot operator; it joins two strings together. In the first statement, $var has the value, "one". The variable, $var identifies the location having, "one". In the second statement, for the right operand " two" is added (joined) into this location, to give the string, "one two". The identification of this location has not changed. So $var still identifies the location. The location is still assigned to $var.

So, to modify the content of a location, we have used the same location instead of two different locations.

Different Memory Locations with Different Variables
Consider the following two consecutive statements:

    $myVar = "I am the content of a large text file from the hard disk, now in memory.";
    $aVar  = "I am the content of a large text file from the hard disk, now in memory.";

You have two different variables with different names but with the same string values. A variable identifies a memory location. Two different variables with two different names identifies two different memory locations, everything being equal. In the above case, the two values, even though are the same, are in two different memory locations.

Same Memory Location for two Different Variables
In PHP you can make the same memory location have two different variables. The two different variables will of course identify the same value. Consider the following consecutive two statements:

    $myVar = "I am the content of a large text file from the hard disk, now in memory.";
    $hisVar  = &$myVar;

For the first statement you have a value assign to the variable, $myVar. In the second statement, $myVar is preceded with the & sign before being assigned to a new variable, $hisVar. & is an operator. In the second statement, the & operator, preceding the first variable, makes the second variable identifies the same memory location (same value) as the first variable. An important thing to note here is that &$myVar refers to a memory location content. You can also say that &$myVar refers to the value in the memory location.

For the second statement, &$myVar, with &, can be considered as a reference, but $hisVar cannot be considered as a reference; please, accept this. $hisVar is a variable, not a reference; just accept this. &$myVar is assigned (not equated) to $hisVar and in the course of being assigned it makes $hisVar identify the same memory location as $myVar; accept this. Accept these three sentences I have just given. Trying to understand why they are like that might make you not to understand PHP referencing.

Now, if you type,

    $myVar = "man";

or

    $hisVar  = "woman";

The content of the same memory location identified by $myVar as well as $hisVar would change. The first statement would change the content to “man” and the second statement would change it to “woman”. With referencing as such, both $myVar and $hisVar identify the same value (memory location).

Using a Reference without Pre-declaration or Assignment
In the previous section, &$myVar was assigned to $hisVar, and $myVar was already declared. You can use a reference without pre-declaration or assignment. A reference consists of & followed by a variable name. The variable name does not have to exist before, as in the above case. In the above case, you have &$myVar, where $myVar existed before. You use such references within expressions and statements. You cannot begin a statement with such reference. You cannot declare a variable with such reference. So you cannot do this:

&$ref = "some value"; //wrong

When you have a reference like &$ref in a code segment, you can assign it to a variable indirectly. An argument, which is a variable declared somewhere, might have assigned to it a reference, during a function call. Something like:

    $theVar = myFn($var1);

where $var1 is a variable declared somewhere (above) in the code. The function, myFn(), returns &$ref during execution, which is assigned to $theVar. We can say, this assignment has been done indirectly.

A reference refers to a memory location. You can use the reference to do whatever you want to do with the memory location, such as modifying the content of the memory location. You can have assigned indirectly the reference to a variable, and then use the content of the memory location, through the variable.

In this article content of a memory location and value (literal), mean the same thing.

When you know the meaning of a reference; that is one stage of understanding referencing. The next thing to do is to learn how to use it. Read on.

Disadvantage of not using a Reference in Certain Situations
Imagine that you have a text file in a hard disk, and the content of this file is now in memory. You might have this content as a string, assigned to a variable, in the normal way, in your code. What you really want to do with such large content from a file, is to change some of its text, delete some of its text or append some new text to the content. After that you save the content back, as a file into the hard disk and you no longer need the content in memory. The following code shows one way to append (add at end) text to such content (it has a disadvantage):

    <?php

        $var1 = "I am the content of a large text file from the hard disk, now in memory.";

        function appendFn($var2)
            {
                $var2 = $var2 . " The last text.";
                return $var2;
            }

        $var1 = appendFn($var1);
        echo $var1;
    ?>

At the beginning of the code, you have the variable, $var1. To this variable is assigned a string value. This string value is short, but let it represent the content of a large text file. Next, you have the function, appendFn(). This function adds the string, " The last text." to the string of the variable, $var1. The function is called as follows:

    appendFn($var1)

where the variable, $var1 is sent as argument. The function itself has the parameter, $var2. When the function is called, this parameter identifies the value of the argument sent. This parameter is actually a variable different from $var1. $var2 holds the value of the argument sent by the calling statement. So just before the function is executed, you have two different variables identifying the same value. However, none of these variables is dealing with referencing, so you have the same value in two different locations in the memory. One of the locations is identified by $var1 and the other is identified by $var2. This status continues until the end of the program execution.

There are two statements in the function definition. The first statement adds the string, " The last text." to the value of the variable, $var2. The second statement returns the value of the variable, $var2. The function calling statement in the code (outside the function definition) receives this value and re-assigns it to the variable, $var1.

In this code, no referencing has been officially used. So the two variables each has its own memory location. One variable is outside the function definition, and the other is inside the function definition. The location for the variable outside the function definition, initially has a string value. After the function call, this location has a piece of string added to it. The location for the variable inside the function definition initially has the string that the location of the variable outside has. The second statement in the function definition adds the piece of string to the location. Note that the technique described above has been used here.

The existence of these two locations is a waste of memory. With referencing, these two locations can be reduced to one location (see below).

Now, memory is always scarce. It is like money, no matter how much you have, you still have reasons to need more money. In the above code, the entire memory has not been used economically. You have to always try to use as little memory as you can when possible. Know that use of referencing leads to an economic use of memory and improved performance of your code.

Passing a Variable by Reference
There are situations when you just need to refer to a memory location, the variable for the memory location is not very important. Wouldn’t it be nice, if you had a reference that simply refers to the location of the $var1 variable in the above code. You use the reference to append the piece of string. After the function call (statement) and execution of the function, you do not need the reference anymore. In this way you will have just one memory location to deal with; not two as before. So you economize memory and there is improved performance. The following code illustrates this (see explanation below):

    <?php

        $var1 = "I am the content of a large text file from the hard disk, now in memory.";

        function appendFn(&$ref)
            {
                $ref = $ref . " The last text.";
                return $ref;
            }

        $var1 = appendFn($var1);
        echo $var1;
    ?>

The code and the previous one are similar. The difference is in the function definition. When the function is called, the variable, $var1 is passed as argument. The parameter of the function is now a reference. The variable part ($ref) of this reference was not previously declared. This reference is not assigned to a new variable and will never be assigned, directly (you will never have anything like, $someVar = &$ref). However, it is indirectly assigned to $var1 at the beginning of the execution of the function. So as the function is executed, both $var1 and &$ref mean the same memory location.

The piece of code you consider as a reference, begins with &, followed by a variable name, e.g. $ref, which starts with the $ signed. Inside the function definition, you use the variable name part preceded by the $ to address the location referred to by the reference. As I said above, after knowing the meaning reference, you have to learn how to use it. In this code, $ref inside the function definition is referring to the same location as $var1 outside. The return statement uses $ref to return the content (value) of the memory location. It does not use &$ref even though &$ref is effectively what the function call returns. It happens here, that the source and destination location of the content are the same.

As you can see, we have used only one memory location instead of two (as in the previous case). We have achieved economy of memory and improved performance.

Function Returning a Reference
In the above code, a reference was returned. However, it is not all the times when the location of the reference is the same as that of the argument passed. Some functions may not have any parameter (so receive no argument), yet you would want it to return a reference. The function in the following code does not receive an argument. The function returns a reference and in the calling statement, the reference is indirectly assigned to a variable.

    <?php

        function &aFn()
            {
                $myVar = "a value";
                return $myVar;
            }

        $theVar = aFn();
        echo $theVar;
    ?>

$myVar is a variable in the ordinary sense in the function definition. It cannot be seen outside the function definition. The second statement of the function definition is supposed to return the value of $myVar. However, because of the & sign preceding the function name in the function definition, a reference to the location of the value of the variable $myVar, is returned. The calling statement assigns this reference to the variable, $theVar. So, the memory location for the content of $theVar (which is outside the function definition) is the same as that for $myVar (which is inside the function definition). Remember, after knowing the meaning of a reference, you need to learn how to use it. You cannot see the reference in this program, in the form of a piece of code, as it was in the case above (&$ref).

So to have a function return a reference officially, precede the function name in the function definition, by &. In the function, return an ordinary variable. When calling the function, do not precede the function name with the & sign.

The new Operator
When you create an object from a class, you do something like this:

    $myObj = new aClass();

Here, new is an operator. It returns a reference that is assigned to a variable.

Reference behaves differently in different computer languages. When you know what a reference is in a computer language, you have to learn how to use it. In other words, you have to learn the different ways in which it is used, in that language.

We have covered a lot for this part of the series. Let us stop here and continue in the next part, with a different topic.

Chrys

Related Links

Major in Website Design
Web Development Course
HTML Course
CSS Course
ECMAScript Course
PHP Course
NEXT

Comments

Become the Writer's Fan
Send the Writer a Message