PDA

View Full Version : [PHP] OO: ho fatto questo esercizio, ma de facto servono ste cose?


Matrixbob
28-07-2010, 16:29
echo '<br><br>- prova di iterazione sugli oggetti: banale -<br>';

class iter{
public $x = 1;
public $y = 2;
}

$obj = new iter();
foreach ($obj as $propriety_name => $prpr_value){
print $propriety_name.': ';
print $prpr_value.'<br>';
}

echo '<br><br>- prova di iterazione sugli oggetti: avanzato -<br>';
// in base all'oggetto implemento i metodi dell'interfaccia
// per farlo comportare come l'array
class ObjectIterator implements Iterator{
private $obj;
private $num;

function __construct($obj){
$this->obj = $obj;
}

function rewind(){
$this->num = 0;
}

function valid(){
return $this->num < $this->obj->max;
}

function key(){
return $this->num;
}

function current(){
echo 'scorro<br>';
switch ($this->num){
case 0: return '1st';
break;
case 1: return '2nd';
break;
case 2: return '3rd';
break;
default: return ($this->num+1).'th';
break;
}
}

function next(){
$this->num++;
}
}

class Object implements IteratorAggregate{
public $max = 10;

function getIterator(){
return new ObjectIterator($this);
}
}

$obj = new Object();
foreach ($obj as $key => $val){
echo "$key = $val<br>";
}

Matrixbob
20-09-2010, 18:13
up, mai usate?