When and Why Is Assigning the Return Value of new by Reference Deprecated?

Susan Sarandon
Release: 2024-10-24 04:12:30
Original
769 people have browsed it

When and Why Is Assigning the Return Value of new by Reference Deprecated?

Assigning the Return Value of new by Reference Deprecation

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>
Copy after login

In the provided example, the code should instead be:

<code class="php">$obj_md =& $mdb2;</code>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!