Skip to content

Language: foreach over object ignores property visibility — leaks private/protected (Zend/zend_execute.c) #23430

Description

@PurHur

Category

bug · php-src-strict · language / object iteration

Problem

Zend foreach ($obj as $k => $v) only yields properties visible from the current scope (same visibility rules as get_object_vars($obj)). The VM iterates every declared instance property regardless of public/protected/private, and also leaks parent private props into a child-class foreach ($this).

Repro Zend 8.2 (2026-07-26) VM (2026-07-26)
external foreach on class with public/protected/private pub=P only pub=P,pro=R,pri=V
foreach ($this) inside declaring class all three props all three (ok)
foreach ($this) in subclass public + protected (+ subclass privates); not parent private includes parent pri=V
anonymous class external foreach (public+private) public only both

php-src reference

PHP implementation target

  • Object-property foreach path in lib/VM/ (and JIT foreach-object helper if shared) — filter by declaring scope / visibility before yielding; match get_object_vars scope rules
  • No new C runtime

Repro

./script/docker-exec.sh -- bash -lc 'cat >/tmp/repro_foreach_vis.php <<'"'"'PHP'"'"'
<?php
class A {
  public $pub = "P";
  protected $pro = "R";
  private $pri = "V";
  public function inside() {
    $ks = [];
    foreach ($this as $k => $v) { $ks[] = "$k=$v"; }
    return implode(",", $ks);
  }
}
class B extends A {
  public function child() {
    $ks = [];
    foreach ($this as $k => $v) { $ks[] = "$k=$v"; }
    return implode(",", $ks);
  }
}
$ks = [];
foreach (new A() as $k => $v) { $ks[] = "$k=$v"; }
echo "ext:", implode(",", $ks), "\n";
echo "in:", (new A())->inside(), "\n";
echo "ch:", (new B())->child(), "\n";
PHP
php /tmp/repro_foreach_vis.php
php bin/vm.php /tmp/repro_foreach_vis.php'

Done when

  • External foreach matches Zend (public only)
  • Inside declaring class / subclass matches Zend visibility (subclass must not see parent private)
  • Compliance .phpt under test/compliance/cases/language/
  • php-src-strict; no php-compiler-strict shortcut

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:vmVirtual machinebugSomething isn't workingimplementation-readySpec complete: repro, php-src ref, done-when — safe for workers to claimphase-2:languagePhase 2 – language features

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions