OOPs Tutorials
- What is OOPs
- Access Modifier
- Constructor
- Destructor
- Polymorphism
- Inheritence
- Method Overriding
- Abstract class
- Interface
- Traits
- This keyword
- static keyword
- Final keyword
- Class Constant
- Exception Handling
- Binding in php
- tostring in php
- Object Iteration
- Reflection
- Magic methods
- Namespaces
- CRUD Function
- OOPs CRUD
- CRUD Example
Important Links
What is Object Iteration?
You want to allow your objects to contain collection of items so that you can loop over them using foreach. You can do that if you implement the php iterator interface, which contains these methods.
Public function current( ) :- return the current element in your collection
Public function key( ) :- return the current key.
Public function next( ) :- return the next element.
Public function valid ( ) :- return true if the current element is valid.
Public function rewind( ) :- starts operations over from the beginning.
Phpiterator, that creates objects you can use in foreach loops. The class here is going to be called DataHandler.
It’s going to use an array internally, because array already support the methods of the iterator interface, .
First you create the DataHandler class, implementing the PHP iterator interface.
This class is going to store an array internally that you pass to its constructor, and let you iterate over that array.
<?php
class DataHandler implements Iterator
{
private $array = array( );
public function __construct($arr)
{
if(is_array($arr))
{
$this->array = $arr;
}
}
}
?>
Now you can use the PHP array functions to write the iterator methods.
<?php
class DataHandler implements Iterator{
private $array = array( );
public function __construct($arr) {
if(is_array($arr)){
$this->array = $arr;
}
}
public function current( ){ return current($this->array); }
public function key( ){
return key($this->array);
}
public function next( ){
return next($this->array);
}
public function valid( ){
return $this->current ( ) !==false;
}
public function rewind ( ) {
reset($this->arraay);
}
}
$new_array = array(“a”, “b”, “c”, “d”);
$obj = new DataHandler($new_array);
Echo “Iterating over the object : <br>”;
Foreach ($obj as $key =>$value)
{
echo $key, ‘ => ‘, $value, “<br>”;
}
?>