php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #45747 Request magic method __iteration()
Submitted: 2008-08-07 22:51 UTC Modified: 2008-08-07 23:09 UTC
From: info at netmosfera dot it Assigned:
Status: Not a bug Package: Feature/Change Request
PHP Version: 5.3.0alpha1 OS: Irrelevant
Private report: No CVE-ID: None
 [2008-08-07 22:51 UTC] info at netmosfera dot it
Description:
------------
Hello, im asking for a magic method in oop

__iteration()

that is how i want it work

a special __get, but for the iteration (foreach)

please just read the code :D

thank you

Reproduce code:
---------------
<?php

class Test
{
   private $pointer = -1;
   private $fields = array();
   private $values = array();

   public function __set($name, $value)
   {
	$this->fields[] = $name;
	$this->values[] = $value;
   }

   public function __get($name)
   {
        list($key) = array_keys($this->fields, $name);
        return $this->values[$key];
   }
   
   public function __iteration($name, $value)
   {
	/*
	my
	useful [...]
	code
	*/
	$this->pointer++;
	return array($this->fields[$this->pointer], $this->values[$this->pointer]);
   }
}

$php = new Test();

$php->just = "a";
$php->a = "b";
$php->simple = "c";
$php->test = "d";

foreach($php as $field => $value)
{
	echo $field . "=" . $value . "<br>";
}

?>

Expected result:
----------------
just = a
a = b
simple = c
test = d

Actual result:
--------------
no result

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2008-08-07 23:09 UTC] johannes@php.net
Have a look at the ITerator and IteratorAggregate interfaces for implementing inner and outer iterators in PHP.
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Sun Aug 17 02:00:03 2025 UTC