user2742648
user2742648

Reputation:

Function returning reference to object property

I've got an event object that looks like this:

class InputEvent
{
    protected $input;

    public function __construct(&$input)
    {
        $this->input = &$input;
    }

    public function getInput()
    {
         return $this->input;
    }
}

Now, since $input is a string, I have to pass it in by reference. However, when I create an event listener, input value doesn't get changed since getInput function returns $input value rather than reference to $input property.

class Listener
{
    public function myEvent(InputEvent $event)
    {
         $input = $event->getInput();

         // doesn't change InputEvent::input property
         $input = "asd";
    }
}

Is there a way for me to return reference to $input value, so that it gets changed inside event object?

I can make two workarounds, but both are.....well, workarounds, not really pretty.

  1. Wrap $input into a class, for example creating a String class which would only hold value and getter, setter methods.

  2. Add setInput method to InputEvent, but still isn't as elegant as just assigning it to a value like in Listener example above.

Upvotes: 2

Views: 2651

Answers (3)

Jon
Jon

Reputation: 4736

class InputEvent
{
    protected $input;

    public function __construct(&$input)
    {
        $this->input = $input;
    }

    public function &getInput()
    {
        return $this->input;
    }
}
$string = "abc";
$a = new InputEvent($string);

$input = &$a->getInput();

$input .= "def";

echo $a->getInput();

Upvotes: 0

Crisp
Crisp

Reputation: 11447

Have your getInput function return by reference

function &getInput()
         ^-- signifies return value by reference

Upvotes: 0

runspired
runspired

Reputation: 2693

As moonwave99 mentioned above, you'll need to use a setter. In your InputEvent class add the method:

public function setInput(&$s) {
    $this->input = $s;
}

Or you could return a reference:

public function &getInputRef() {
    return $this->input;
}
$input = &$event->getInputRef();

Which I think should work the same.

Upvotes: 2

Related Questions