Passing an array of objects using a method reference

I have a method in my class that takes an object by reference. It decorates this object to expand functionality.

primarily...

public function addObject( &$object ) {
    $object = $this->decorate( $object );
}

I am trying to write a convenience method addObjects(), but it does not change$object

This does not work...

public function addObjects( array &$objects ) {
    foreach( $objects as $object ) {
        $this->addObject( $object );
    }
}

I tried a bunch of other routes but no one worked. I am sure there is a way to do this, but it eludes me. Perhaps I looked at my computer for too long.

Here is a living example

http://ideone.com/tfopZ


Update

There seems to be no way to pass references when creating an array of objects

$objects = array( &$object1, $object2 ); //object1 will be decorated, object2 will not
$thing->addObjects( $objects );
+3
source share
2 answers

EDIT: , , - , :

$dec->addObjects( $a);
$std = $a[0];
print_r( $std );

$std .

decorator Object
(
    [decoratee:protected] => stdClass Object
        (
        )

)

, , .

, . , , :

$a = array( $std );

, :

  • .

, $std , , $std, , , :

$std = new StdClass;

decorator test , $a .

, , PHP , , :

$a = array( &$std );

, , , .

+4

, foreach( $objects as $object ). $object. foreach( $objects as & $object ).

foreach PHP

+1

Source: https://habr.com/ru/post/1775341/


All Articles