What happens when an object is passed by reference in PHP?
When an object is passed by reference in PHP, any changes made to the object within the function will affect the original object outside of the function as well. To pass an object by reference in PHP, you can use the "&" symbol before the parameter in the function declaration.
class MyClass {
public $value;
public function __construct($value) {
$this->value = $value;
}
}
function modifyObject(MyClass &$obj) {
$obj->value = "Modified";
}
$obj = new MyClass("Original");
echo $obj->value; // Output: Original
modifyObject($obj);
echo $obj->value; // Output: Modified
Related Questions
- What are the limitations of using include or readfile functions for displaying external content on a webpage?
- What are the potential pitfalls of using PHP to sort data compared to using SQL queries for sorting?
- What are the best practices for handling form data selection and processing in PHP to ensure smooth data flow?