Graham Hill
Graham Hill

Reputation: 13

Cannot access variable property with getter method

In PHP, I cannot assign a value to a variable unless I access its property without using a getter method, is it by design or I missed something?

Simply put, when I do $article->content->value[$some_value] = 'hello' it works, but $article->get_value()[$some_value] = 'hello' sets nothing, the array remains empty.

What the get_value does is just return $this->content->value, and when used as a getter, it does what it supposed to do as expected.

I feel like I missed some basic here, if someone could share me why setting value doesn't work, it'll be great.

Upvotes: 1

Views: 386

Answers (1)

iainn
iainn

Reputation: 17417

Unlike objects, arrays aren't returned by reference in PHP, so when you call the getter method, you're getting back a copy.

If you want to modify the object property itself then you can change the method definition to return a reference by prepending the method name with an ampersand, e.g.

public function &getArray()
{
    return $this->array;
}

See https://3v4l.org/1YK9H for a demo

I should stress that this is absolutely not a common pattern in PHP, other than perhaps a long way back into the PHP 4 days when OOP was a lot less ubiquitous. I certainly wouldn't expect a class I was using to return arrays by reference, and neither would I recommend anyone else doing it. Note that it's not possible to ask the class for a reference, in order to prevent unwanted modifications to private properties - the class has to define the behaviour.

The PHP documentation has more information about returning by reference here: http://php.net/manual/en/language.references.return.php

Upvotes: 2

Related Questions