Skip to content

Instantly share code, notes, and snippets.

@nezarfadle
Last active September 20, 2017 05:33
Show Gist options
  • Save nezarfadle/dccc07ed0cc73a1cc29cecc8a9375411 to your computer and use it in GitHub Desktop.
Save nezarfadle/dccc07ed0cc73a1cc29cecc8a9375411 to your computer and use it in GitHub Desktop.
<?php
/**
* A better way to iterate over an collection
*/
$itemsArray = [ 1, 2, 3 ];
/**
* Legacy code
*/
foreach ( $itemsArray as $key => $item ) {
echo $item;
}
/**
* A better code
*/
class Items
{
private $array;
public function __construct( $array )
{
$this->array = $array;
}
public function each( $cb )
{
foreach ( $this->array as $key => $value ) {
$cb( $key, $value );
}
}
/** More logic can be added here **/
public function isEmpty(){}
public function has( $value ){}
}
$items = new Items( $itemsArray );
$items->each( function( $key, $item ){
echo $item;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment