PHP References Vs. Object Handles
Instructions:
Parameter Scope
When you pass a variable to a function in PHP and the function modifies the value of the variable, it has no effect on the variable’s value outside the scope of the function. To allow a function to modify the value of a variable, you must specifically declare this intent by prefixing the variable name with an ampersand in the function definition. For example:
function modify_param,(¶m) {
}
Value or Reference
A function can’t modify a variable’s value outside its own scope because PHP passes the variable by value. It creates a copy of the variable’s value and passes the copy to the function. Any changes to that value affect only the local copy. When you pass by reference using the ampersand in the function definition, PHP passes a pointer to the memory address space containing the value of the variable. Operations on the variable are then performed against the global value of the variable, not a copy of its value.
Passing Objects
When you pass an object as a parameter to a function, PHP still passes the object by value, but it passes a different kind of value. A copy of an object handle, or identifier, is passed to the function. The object identifier allows the function to find the memory address space where the values of the object members are stored. This means that an object’s members are actually passed by reference. Operations that use an object’s properties and methods manipulate the memory address space of those members and change their global values.
Object Handle Copy
Not all objects in PHP are passed by reference, even though changes to the object members affect global values. A copy of the object handle is passed to a function. If a function makes an assignment that changes the object handle itself, that change does not modify the object handle since it is passed by value. To allow a function to modify the object’s handle, you must pass the object by reference, just as you would with any other variable in PHP.
Sign up for our daily email newsletter:
You must log in to post a comment.