Problem Statement
Attempting to assign the return value of new by reference triggers the PHP error "Assigning the return value of new by reference is deprecated."
In-Depth Explanation
This error occurs when trying to assign the result of new (used to create a new object) to a variable using the reference operator (&). In PHP4, this idiom was commonly used to pass the reference of an object to another variable. However, in PHP5, this practice has been deprecated due to potential misuse and confusion.
Solution
The correct syntax for assigning an object reference is:
<code class="php">$variableName =& $objectName;</code>
In the provided example, the code should instead be:
<code class="php">$obj_md =& $mdb2;</code>
Additional Note
The deprecated idiom assigns the return value of new directly to a variable using the reference operator. For instance:
<code class="php">$obj_md =& new MDB2();</code>
This practice was not only deprecated in PHP5 but also resulted in unexpected behavior if the variable was previously defined.
To avoid the deprecation warning and ensure the code behaves correctly, use the revised syntax with the =& operator to assign references to objects.
The above is the detailed content of When and Why Is Assigning the Return Value of new by Reference Deprecated?. For more information, please follow other related articles on the PHP Chinese website!