Forum Moderators: coopster

Message Too Old, No Replies

Child class member's Iteration by parent class

any way for parent class function iterate private members of child class?

         

sunswept

6:54 pm on Mar 1, 2007 (gmt 0)

10+ Year Member



I have a class that has a few private members. Is there a way to create a function in its parent class that can access its (child's) private members.

With the following code I am able to get only the public and protected members.

class parentIter {

function iterateProps ( ) {

foreach ( $this as $propName => $propValue ) {

echo "<br>$propName => $propValue" ;
}
}
}

class childIter extends parentIter {

protected $var1 = 'protected var' ;
private $var2 = 'private var' ;
public $var3 = 'public var' ;

function iterateProps ( ) {
parent::iterateProps () ;
}
}

$obj = new childIter () ;
$obj->iterateProps ( ) ;

eelixduppy

9:47 pm on Mar 1, 2007 (gmt 0)



That's the whole idea behind private members: they cannot be accessed outside of the class. So I don't think what you want to do is possible when it's private. I do find the following codes output rather interesting, though:

class parentIter {

function iterateProps ( ) {

foreach ( $this as $propName => $propValue ) {
#echo "<br>$propName => $propValue";
echo '<pre>';
print_r(get_defined_vars());
echo '<pre>';
}
}
}

You'll see that it is actually in there...but not ;)

There's more on this here: Visibility [us3.php.net].

Good luck!

sunswept

5:54 am on Mar 2, 2007 (gmt 0)

10+ Year Member



I do see that it IS there but Isnt!
Thanks

Still, I think there can be legitimate cases for wanting such accesiblity. Consider this:
1. I want only my (child) class functions to change value of a member (validation requirements) so i have to make it private.
2. several classes (and our child class) need a print function for all their vars.
3. The best way seems to put an iteration function in the parent and call it from each child like in code above.

I am not sure if other oop languages impose the same restricions.

Any thoughts?