eval.in

Paste #39494

PHP — PHP 5.4.6, pasted 4 years ago (json)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<?php
/**
 * Advanced PHP Interface Example: Traversable and Countable extended
 *
 * As Traversable is an internal interface but PHP interfaces allow to extend
 * from multiple interfaces, it is possible to create your own internal
 * type (here based on Traversable) and base another non-internal sub-type 
 * on it (here based on IteratorAggregate).
 *
 * @link http://wpkrauts.com/2013/how-to-build-flexible-php-interfaces/
 * @link https://eval.in/39494
 */

interface CountableTraversable 
    extends Traversable, Countable
{
}

interface CountableTraversableAggregate 
    extends CountableTraversable, IteratorAggregate
{
}

class Widgets implements CountableTraversableAggregate
{
    private $widgets = array('Blue', 'Red');
    
    function getIterator() 
    {
        return new ArrayIterator($this->widgets);
    }

    function count() 
    {
        return count($this->widgets);
    }
}

$widgets = new Widgets();

printf("You have %d widgets:\n", count($widgets));

foreach($widgets as $key => $widget) {
    printf("[%s]: %s\n", $key, $widget);
}

Program Output

You have 2 widgets:
[0]: Blue
[1]: Red

OK (0.008 sec real, 0.006 sec wall, 13 MB, 44 syscalls)

Fork