Last active
September 20, 2017 05:33
-
-
Save nezarfadle/dccc07ed0cc73a1cc29cecc8a9375411 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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