Are PHP variables passed by value or by reference?
original title: "Are PHP Variables passed by value or by reference?"
Are PHP variables passed by value or by reference?
क्या PHP वैरिएबल मूल्य या संदर्भ द्वारा पारित किए जाते हैं?
यह अनुवाद के बाद का सारांश है, अगर आपको पूरा अनुवाद देखने की आवश्यकता है, तो कृपया 'अनुवाद' आइकन पर क्लिक करें
It's by value according to the PHP Documentation.
It seems a lot of people get confused by the way objects are passed to functions and what pass by reference means. Object variables are still passed by value, its just the value that is passed in PHP5 is a reference handle. As proof:
Outputs:
To pass by reference means we can modify the variables that are seen by the caller. Which clearly the code above does not do. We need to change the swap function to:
Outputs:
in order to pass by reference.
In PHP, By default objects are passed as reference copy to a new Object.
See this example.............
Now see this..............
Now see this ..............
i hope you can understand this.
http://www.php.net/manual/en/migration5.oop.php
PHP variables are assigned by value, passed to functions by value, and when containing/representing objects are passed by reference. You can force variables to pass by reference using an &
Assigned by value/reference example:
would output
Passed by value/reference exampe:
would output:
Object variables passed by reference exampe:
Would output:
(that last example could be better probably...)
You can pass a variable to a function by reference. This function will be able to modify the original variable.
You can define the passage by reference in the function definition:
You can do it either way.
put a '&' symbol in front and the variable you are passing becomes one and the same as its origin. ie: you can pass by reference, rather than making a copy of it.
so
Variables containing primitive types are passed by value in PHP5. Variables containing objects are passed by reference. There's quite an interesting article from Linux Journal from 2006 which mentions this and other OO differences between 4 and 5.
http://www.linuxjournal.com/article/9170
Objects are passed by reference in PHP 5 and by value in PHP 4. Variables are passed by value by default!
Read here: http://www.webeks.net/programming/php/ampersand-operator-used-for-assigning-reference.html
Attributes are still modifiable when not passed by reference so beware.
Output:
SwapObjects: b, a SwapValues: a, b
Actually both the methods are valid but it depends upon your requirement.Pass values by reference often makes your script slow. So its better to pass variables by value by considering time of execution. Also the code flow is more consistent when you pass variables by value.
Use this for functions when you wish to simply alter the original variable and return it again to the same variable name with its new value assigned.
Depends on the version, 4 is by value, 5 is by reference.