jeudi 5 mars 2015

Inconsistencies in looping through the private properties of a subclass

I was trying to loop through the private properties of a class. The method which would perform this loop is contained in a parent class. Consider the following code:



class ChildClass extends ParentClass {
private $childProp = "childPropValue";
}

class ParentClass {
private $parentProp = "parentPropValue";

public function PrintProperties()
{
echo "--- print_r(\$this) ---\n";
print_r($this);

echo "\n\n--- foreach(\$this) ---\n";
foreach($this as $propKey => $propValue) {
print_r($propKey . ":");
print_r($propValue . "\n");
}

echo "\n\n--- reflection->getProperties ---\n";
$refl = new \ReflectionClass($this);
print_r($refl->getProperties());
}
}

$child = new ChildClass();
$child->PrintProperties();


This outputs:



--- print_r($this) ---
ChildClass Object
(
[childProp:ChildClass:private] => childPropValue
[parentProp:ParentClass:private] => parentPropValue
)


--- foreach($this) ---
parentProp:parentPropValue


--- reflection->getProperties ---
Array
(
[0] => ReflectionProperty Object
(
[name] => childProp
[class] => ChildClass
)

)


Now, the results for reflection make sense to me. This is a 'Child' class and to only accessible property is the 'childProp'. What does seem weird is the result of the foreach loop and the print_r of $this.


The print_r($this) correctly identifies $this as a ChildClass object and it then lists 2 private properties for this object. Only one of those is accessible from within a ChildClass, namely the $childProp. It, however, prints both properties, which is a little strange, but at least it correctly identifies the object for the property. It could be argued that print_r is only for debugging purposes, so printing both properties is useful in that regard.


Now, the foreach($this) loop uses the same variable as the print_r, but here it seems like $this is identified as a ParentClass object, since the only property which is printed is the $parentProp property.


I think this is unintuitive and inconsistent behaviour and was wondering if this is a bug. Especially the foreach loop seems wrong to me. Can someone make sense of these results?






Aucun commentaire:

Enregistrer un commentaire