|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2005-09-11 22:27 UTC] stochnagara at hotmail dot com
Description:
------------
There is some incostistency with foreach and a class which has __get and __set methods. I don't know what is the intended behaviour but there is a problem there when assigning a foreach key or value to an overloaded member of such class.
See comments in the expected result region.
Reproduce code:
---------------
<? class abc {
function __set ($key, $value) { echo "__set ($key,$value)<br/>"; $this->arr[$key] = $value; }
function /*&*/ __get ($key) { echo "__get ($key)<br/>"; return $this->arr[$key]; }
function __isset ($key) { echo "__isset ($key)<br/>"; return isset ($this->arr[$key]); }
function __unset ($key) { echo "__unset ($key)<br/>"; unset ($this->arr[$key]); }
private $arr;
}
$abc = new abc();
foreach (array (1,2,3) as $abc->k => $v) {
print_r($abc);echo ';'; var_dump($abc->k);echo ';';
}
$abc->k = 4;
echo '-----<br/>';
foreach (array (1,2,3) as $abc->k => $v) {
print_r($abc);echo ';'; var_dump($abc->k);echo ';';
}
echo '<br/>-----<br/>';
$abc_value = new abc();
foreach (array (1,2,3) as $v => $abc_value->k) {
print_r($abc_value);echo ';'; var_dump($abc_value->k);echo ';';
}
Expected result:
----------------
Depends of specification.
Case 1 : First foreach fills $arr with keys. Others are ok.
Case 2 : Second foreach does not fill $arr with keys.
Note 1!
When __get is changed to return by reference, first foreach behaves exactly like the second one.
Note 2!
Third foreach calls __set while first and second do not.
Actual result:
--------------
__get (k)
abc Object ( [arr:private] => Array ( ) ) ;__get (k)
NULL ;__get (k)
abc Object ( [arr:private] => Array ( ) ) ;__get (k)
NULL ;__set (k,4)
-----
__get (k)
abc Object ( [arr:private] => Array ( [k] => 0 ) ) ;__get (k)
int(0) ;__get (k)
abc Object ( [arr:private] => Array ( [k] => 1 ) ) ;__get (k)
int(1) ;
-----
__set (k,1)
abc Object ( [arr:private] => Array ( [k] => 1 ) ) ;__get (k)
int(1) ;__set (k,2)
abc Object ( [arr:private] => Array ( [k] => 2 ) ) ;__get (k)
int(2) ;
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Sun Oct 26 17:00:01 2025 UTC |
That's the shortest I can (run this sample with function & __get too). <? class abc { function __set ($key, $value) { $this->arr[$key] = $value; } function __get ($key) { return $this->arr[$key]; } private $arr; } $abc = new abc(); foreach (array (1,2,3) as $abc->k => $v) print_r($abc); $abc->k = 4; foreach (array (1,2,3) as $abc->k => $v) print_r($abc); $abc_value = new abc(); foreach (array (1,2,3) as $v => $abc_value->k) print_r($abc_value); ?>