Friday, June 5, 2009

Object iteration 1/2

the construct foreach in PHP5 supports also object, in addition to arrays.

foreach($object as $key=>$val)
{
//$key will be equal to the nth member name
//$val will be equal to the nth member value
}

Which members are visibile ? it depends on the "foreach" position !
  • inside the class ($this is the object): all the members are visibile
  • outside the class: only public members are visible
  • inside an inherited class: public and protected
Example:

class A
{
public $a;
public
$b;
private
$p;
public function
__construct($a, $b, $p){
$this->a = $a;$this->b = $b; $this->p = $p;
}
public function
f()
{

foreach(
$this as $k=>$v)

{print "$k => $v \n"; }
}
}

$a = new A(1,2,3);

foreach(
$a as $k=>$v)
{
print "$k => $v \n";
} //a => 1 b => 2

$a->f(); //a => 1 b => 2 p => 3

No comments:

Post a Comment

 

PHP and tips|PHP