why is direct access to an array not possible using a magic __set() method?
Ok, so here's a snippet of my 开发者_高级运维Properties
base class, that is extended in most of the classes in my application:
class Properties {
protected $properties_arr = array();
/**
* Magic function to be able to access the object's properties
* @param string $property
*/
public function __get( $property ) {
if ( array_key_exists( $property, $this->properties_arr ) ) {
return $this->properties_arr[ $property ];
}
return $this->getUndefinedProperty( $property );
}
/**
* Magic function to be able to access the object's properties
* @param string $property
* @param mixed $value
*/
public function __set( $property, $value ) {
if ( property_exists( $this, $property ) ) {
$this->setProtectedProperty( $property );
}
$this->properties_arr[ $property ] = $value;
}
It's pretty basic, and there's nothing wrong with it, but I'm running into a problem that I've encountered a couple times before, and it's that you can't perform certain actions on an array
property through the __get method.
Doing this, for instance:
$MyClass = new Properties();
$MyClass->test = array();
$MyClass->test['key'] = 'value';
you would expect the $MyClass->test
array to contain one item, but it's still an empty array! Now I know I can work around it by just assigning an array with the items already in it, but I would just really like to know why this is (and if there's a better solution).
Thanks!
See PHP Accessor functions and arrays.
The issue is probably that you need to make the __get() method return a reference.
This is because you need to also override the __isset magic method to check if the array index exists.
精彩评论