php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #31762 array_shift() modifies array passed by value from class method
Submitted: 2005-01-30 05:38 UTC Modified: 2005-02-05 05:41 UTC
From: e at narod dot ru Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 5.0.3 OS: Windows XP
Private report: No CVE-ID: None
View Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
If you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: e at narod dot ru
New email:
PHP Version: OS:

 

 [2005-01-30 05:38 UTC] e at narod dot ru
Description:
------------
Function array_shift() modifies array passed by value from class method.

In the example below $_cache is modified through array_shift() call though $_cache is always passed by value.

The bug doesn't appear if we don't use classes.





Reproduce code:
---------------
class A {
	var $_cache = false;

	function get_array() {
		if (!$this->_cache) $this->_cache = array(1, 2, 3, 4, 5);
		return $this->_cache;
	}
	function get_shifted_array() {
		return array_shift($this->get_array());
	}
}
$a = new A;
for ($i = 0; $i < 5; $i++)
	echo $a->get_shifted_array() . "\n";


Expected result:
----------------
1
1
1
1
1


Actual result:
--------------
1
2
3
4
5


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2005-02-03 21:52 UTC] tony2001@php.net
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to report
a bug at http://bugs.php.net/how-to-report.php

That's how it works.
See http://php.net/array_shift
 [2005-02-05 05:41 UTC] e at narod dot ru
How can you explain Try to remove the line:

"if (!$this->_cache) $this->_cache = array(1, 2, 3, 4, 5);"

and you'll get

"PHP Fatal error:  Only variables can be passed by reference in C:\TEMP\bug31762.php on line 10"

The strange thing is that "if (...)" statement influences the function's return value type.why the problem
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Sun Jul 20 21:00:02 2025 UTC