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 $_SESS开发者_StackOverflow中文版ION['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.
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)
.
精彩评论