In PHP 5, are objects passed by reference by default or by value?
In PHP 5, objects are passed by reference by default. This means that when you pass an object to a function or assign it to a variable, you are actually passing a reference to the object in memory, not a copy of the object itself. If you want to pass objects by value instead of by reference, you can use the clone keyword to create a copy of the object.
class MyClass {
public $value;
}
$obj1 = new MyClass();
$obj1->value = 5;
// Passing object by reference
function updateValueByReference($obj) {
$obj->value = 10;
}
updateValueByReference($obj1);
echo $obj1->value; // Output: 10
// Passing object by value using clone
$obj2 = clone $obj1;
$obj2->value = 15;
echo $obj1->value; // Output: 10
echo $obj2->value; // Output: 15
Related Questions
- In PHP, what is the significance of using srand() before calling the rand() function, and how does it affect the random number generation process?
- What are common methods in PHP to preserve tab spacing in code snippets entered into input fields?
- What is the best practice for decoding iso-8859-1 text from email headers in PHP?