Home > Backend Development > PHP Tutorial > Why Does PHP Issue 'Strict Standards: Only variables should be passed by reference' When Using array_shift()?

Why Does PHP Issue 'Strict Standards: Only variables should be passed by reference' When Using array_shift()?

Mary-Kate Olsen
Release: 2024-12-20 07:39:11
Original
616 people have browsed it

Why Does PHP Issue

Understanding Reference Passing in PHP: Strict Standards and Array_Shift()

In PHP, strict standards mode can issue warnings when passing non-variable values by reference. A common example of this is when using the array_shift() function.

When Does the Warning Occur?

The "Strict standards: Only variables should be passed by reference" warning appears when array_shift() is used with a non-variable value passed as an argument. For instance:

$instance = new MyClass();
$el = array_shift($instance->find(...)); // Warning
Copy after login

In contrast, when array_shift() is called with a variable containing an array, no warning is generated:

function get_arr() {
    return [1, 2];
}
$el = array_shift(get_arr()); // No warning
Copy after login

Non-Intuitive Behavior

The warning can be confusing because array_shift() is a function that returns an array value. However, under strict mode, PHP considers the return value of array_shift() as a non-variable.

Resolving the Warning

To resolve the warning in strict mode, there are two options:

  1. Modify the Method Signature: Change the signature of the method returning the array to avoid using a reference.
  2. Use an Intermediate Variable: Assign the array returned by the method to an intermediate variable before passing it to array_shift().

For example:

// Modify Method Signature
function get_arr() {
    return [1, 2];
}
$instance = new MyClass();
$el = array_shift($instance->get_arr());

// Use Intermediate Variable
$el = array_shift($instance->get_arr() ?: []);
Copy after login

The above is the detailed content of Why Does PHP Issue 'Strict Standards: Only variables should be passed by reference' When Using array_shift()?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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