1

I have a class called PreferenceCollection, which I load for a user into $_SESSION['Preferences'] once they log in to my web application. This simple class uses magic methods for getting and setting values. Here are the relevant parts:

class PreferenceCollection {
    private $prefs;

    function __construct() {
        $this->prefs=Array();
    }

    function __get($var) {
        return $this->prefs[$var];
    }

    function __set($var, $value) {
        $this->prefs[$var]=$value;
        $this->save();
    }
}

Later on in my code, I have found it necessary to set the value of a dynamically chosen property. For this example, $key='pref_some_preference' and value='something'.

$_SESSION['Preferences']->substr($key, 5)=$value;

What I expect is the equivalent of $_SESSION['Preferences']->some_preference=$value. That is, the __set magic method will be called with the first parameter of some_preference, and the second parameter, $value.

Instead, this line gives me a fatal error:

PHP Fatal error: Can't use method return value in write context

I assume that PHP is interpreting that I want to set the return value of the substr() call to something, rather than setting the property.

Is my interpretation of what is happening correct? How would I get around this problem?

For now I am working around the issue with a public set method, but am curious how I could set that property directly.

2
  • It isn't clear what the line you give is supposed to do. Can you give a more detailed example so we can suggest a solution? Commented Aug 1, 2011 at 19:17
  • @Jon, I have added some clarification. Please let me know if there are additional questions, or my question is still unclear. Commented Aug 1, 2011 at 19:20

1 Answer 1

3

I think you want

$_SESSION['Preferences']->{substr($key, 5)} = $value;

The braces {} are required to guide the PHP parser into the correct direction ;-) Given that $key is 12345test this would call __set('test', $value).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.