xref: /PHP-8.0/ext/spl/tests/spl_004.phpt (revision 68195bd4)
1--TEST--
2SPL: iterator_apply()
3--FILE--
4<?php
5
6function my_error_handler($errno, $errstr, $errfile, $errline) {
7    echo "Error: $errstr\n";
8}
9
10set_error_handler('my_error_handler');
11
12function test_arg($arg)
13{
14    if ($arg instanceof Iterator)
15    {
16        var_dump($arg->key());
17        var_dump($arg->current());
18    }
19    else
20    {
21        var_dump($arg);
22    }
23    return true;
24}
25
26function test()
27{
28    static $arg = 0;
29    var_dump($arg++);
30    return true;
31}
32
33$it = new RecursiveArrayIterator(array(1, array(21, 22), 3));
34
35var_dump(iterator_apply($it, 'test', NULL));
36
37echo "===ARGS===\n";
38var_dump(iterator_apply($it, 'test_arg', array($it)));
39
40echo "===RECURSIVE===\n";
41$it = new RecursiveIteratorIterator($it);
42var_dump(iterator_apply($it, 'test'));
43
44echo "===ERRORS===\n";
45try {
46    var_dump(iterator_apply($it, 'test', 1));
47} catch (TypeError $e) {
48    echo $e->getMessage(), "\n";
49}
50try {
51    var_dump(iterator_apply($it, 'non_existing_function'));
52} catch (TypeError $e) {
53    echo $e->getMessage(), "\n";
54}
55try {
56    var_dump(iterator_apply($it, 'non_existing_function', NULL, 2));
57} catch (TypeError $e) {
58    echo $e->getMessage(), "\n";
59}
60
61?>
62--EXPECT--
63int(0)
64int(1)
65int(2)
66int(3)
67===ARGS===
68int(0)
69int(1)
70int(1)
71array(2) {
72  [0]=>
73  int(21)
74  [1]=>
75  int(22)
76}
77int(2)
78int(3)
79int(3)
80===RECURSIVE===
81int(3)
82int(4)
83int(5)
84int(6)
85int(4)
86===ERRORS===
87iterator_apply(): Argument #3 ($args) must be of type ?array, int given
88iterator_apply(): Argument #2 ($callback) must be a valid callback, function "non_existing_function" not found or invalid function name
89iterator_apply() expects at most 3 arguments, 4 given
90