fork download
  1. <?php
  2. class Foo {
  3. public $name;
  4. public $type;
  5.  
  6. public function __construct($name, $type) {
  7. $this->name = $name;
  8. $this->type = $type;
  9. }
  10.  
  11. public function searchZeroType($o) {
  12. return ($o->type == 0);
  13. }
  14.  
  15. public function doubleType($o) {
  16. return $o->type = $o->type * 2; //Почему не получилось c return $o->type * 2;
  17. }
  18. }
  19.  
  20. class SplObjectFunctions {
  21. public static function object_filter(callable $c, $objectStorage) {
  22. $s = new SplObjectStorage();
  23.  
  24. foreach($objectStorage as $object) {
  25. if ($c($object)) {
  26. $s->attach($object);
  27. }
  28. }
  29.  
  30. return $s;
  31. }
  32.  
  33. public static function object_map(callable $c, $objectStorage) {
  34. $s = $objectStorage;
  35.  
  36. foreach($s as $object) {
  37. $c($object);
  38. }
  39.  
  40. return $s;
  41. }
  42. }
  43.  
  44. $a = new SplObjectStorage();
  45.  
  46. $a->attach(new Foo('first', 1));
  47. $a->attach(new Foo('second', 1));
  48. $a->attach(new Foo('third', 0));
  49. $a->attach(new Foo('fourth', 1));
  50.  
  51.  
  52. $search = SplObjectFunctions::object_filter(array('Foo', 'searchZeroType'), $a);
  53. $double = SplObjectFunctions::object_map(array('Foo', 'doubleType'), $a);
  54.  
  55. print_r($double);
Success #stdin #stdout 0.02s 24448KB
stdin
Standard input is empty
stdout
SplObjectStorage Object
(
    [storage:SplObjectStorage:private] => Array
        (
            [000000004e27674a00000000752cabe3] => Array
                (
                    [obj] => Foo Object
                        (
                            [name] => first
                            [type] => 2
                        )

                    [inf] => 
                )

            [000000004e27674b00000000752cabe3] => Array
                (
                    [obj] => Foo Object
                        (
                            [name] => second
                            [type] => 2
                        )

                    [inf] => 
                )

            [000000004e27674c00000000752cabe3] => Array
                (
                    [obj] => Foo Object
                        (
                            [name] => third
                            [type] => 0
                        )

                    [inf] => 
                )

            [000000004e27674d00000000752cabe3] => Array
                (
                    [obj] => Foo Object
                        (
                            [name] => fourth
                            [type] => 2
                        )

                    [inf] => 
                )

        )

)