Broad Network


Unsetting and Spotting References

Understanding PHP Reference – Part 4

Forward: In this part of the series, we see how to unset a reference and how to spot a reference.

By: Chrysanthus Date Published: 9 Aug 2012

Introduction

This is part 4 of my series, Understanding PHP Reference. In this part of the series, we see how to unset a reference and how to spot a reference.

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.

Unsetting a Reference
This is what the specification says about unsetting a reference: “When you unset the reference, you just break the binding between variable name and variable content. This does not mean that variable content will be destroyed.” The following code illustrates this:

<?php

        $myVar = 56;
        $herVar = &$myVar;

        echo "myVar is ".$myVar."<br />";
        echo "herVar is ".$herVar."<br />";

        unset($herVar);

        echo "myVar is ".$myVar."<br />";
        echo "herVar is ".$herVar."<br />";

?>

PHP has a predefined function called, unset(). This function is used to break the binding between a variable and the region in memory that has the value. After that, the variable no longer refers to that region. The argument to this function is the variable whose binding you want to break from the region in memory. After the unset, the variable no longer refers to that region and you can no longer use the variable for the value in the region. The value remains in the region and might be referred to by other variables. Read and try the above code if you have not already done so.

Spotting References
Many syntax constructs in PHP are implemented through referencing mechanisms. The previous parts of the series have treated this topic indirectly. In this section, we talk about some of the things left. In order to understand this section you need knowledge on Variable Scope in PHP. If you do not have that knowledge, then read the series titled, “Understanding Variable Scope in PHP”, that I wrote in this blog.

When you declare a variable as global inside a function, like,

    global &var0;

you are creating a reference of this variable in the $GLOBALS associative array. The key in the $GLOBALS array that would return the value of the variable, is a kind of reference to the value.

The Predefined $this Variable
When you study PHP Object Oriented Programming, you will learn that the predefined $this variable is a reference.

This is a rather short tutorial. Let us end here and continue in the next part of the series.

Chrys

Related Links

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

Comments

Become the Writer's Fan
Send the Writer a Message