Foreach() Skips Uninitialized Properties¶
<?php
class z {
public readonly int $p;
public readonly int $q;
public function __construct()
{
$this->p = 1;
}
}
$x = new z;
// foreach skips undefined properties, readonly or not
foreach($x as $k => $v) {
print $k . " " . $v . PHP_EOL;
}
echo $x->q;
?>
Foreach() reads naturally all public properties in an object. Protected and private are omitted, unless in the right context.
Foreach() also skips silently uninitialized properties: this prevents the generation of NULL values, but also, skips all readonly properties: any direct hit on such property would otherwise generate a Fatal error.
See Also¶
PHP Features¶
Last updated: 14 July 2026