,
Share with your friends 

Pass by value and pass by reference dilema in PHP

2 ratings Views 205 
Author: Trupti (Trupti Jain)  View Profile |  View other solutions by this author

Question / Problem


PHP deals with variables in very strange manner.In case of a variable which is assigned some value through pass by reference mechanism,any chnge in this newly assigned varriable will reflect in all previous assignments and create serious problems.

Solution

As far as memeory usage are concerned, PHP programmers must use pass by Value method.In case if we use pass by reference in any PHP function then any change in the new assigned varriable ipact the previous assignments.this thing is applicable in case of PHP objects also as they internally use pass by reference.

Internally PHP deals with the variables with some variable containers also known as ZVAL.
Whenever a variable is assigned some value then its stored in ZVAL variable.Any further variable declaration to the same value point to the same zval variable location and refcount is incremented in that case.In case if the value assigned is pass by reference then is_ref is also set to true.

So each time we go for a pass by reference method for assignment a new zval is created and increase memeory usage.Next time when this reference is again assigned by pass by vale to some next variable ,and the next variable do some changes with it.The change is reflected on all previous variables which were using the sam reference value.

There are three things in these Zval
1. Actual value of the variable
2. Ref Count
3. Is_ref






Applies to

PHP

Rank It

Login to rank it

Report


Advertisement