|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2007-07-08 20:03 UTC] robin at soal dot org
Description:
------------
The documentation states that "all visible properties will be used for the iteration" when foreach'ing over an object.
Below is a case where this is not true.
Reproduce code:
---------------
<?php
class C {
private $priv = "A private variable";
function doLoop() {
echo "Proof that the private is visible: " . $this->priv . "\n";
foreach ($this as $k=>$v) {
echo "The private is visible so should be accessed in the loop:\n";
echo "-> $k: $v";
}
}
}
class D extends C {}
$myD = new D;
$myD->doLoop();
?>
Expected result:
----------------
Proof that the private is visible: A private variable
The private is visible so should be accessed in the loop:
-> priv: A private variable
Actual result:
--------------
Proof that the private is visible: A private variable
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Thu Oct 30 22:00:01 2025 UTC |
Hi Judas, Thanks for the comment. I think we may have the same understanding of visibility in this case: D extends C, so $priv (which is defined in C) should only be visible on instances of D if the current context is C. If $priv is visible when using the object operator on $this, I think it is justified that it would be visible when using foreach on $this from the same context. In case my use of $this was confusing the issue, here's the same problem presented without $this (same expected and actual output as above): <?php class C { private $priv = "A private variable"; static function doLoop(D $myD) { echo "Proof that the private is visible: " . $myD->priv . "\n"; foreach ($myD as $k=>$v) { echo "The private is visible so should be accessed in the loop:\n"; echo "-> $k: $v"; } } } class D extends C {} $myD = new D; C::doLoop($myD); ?>