Hi,

I have an interesting problem that I cannot explain with using the
__set() and __get() when playing with arrays.

Basically with a normal object if you store an array as a property you
can manipulate it like an array. eg.

$obj->prop[5] = 'apple';

In this example if $obj->prop is an array then the position 5 will then
contain 'apple'. This is expected behaviour and works very well.

Now if you use the following code and use overloading you can do the
same thing.

--8<--
<?php

class ex {
  public function __get($prop) {
    echo "getting property $prop\n";
    return $this->fields[$prop];
  }

  public function __set($prop, $value) {
    echo "setting property $prop\n";
    $this->fields[$prop] = $value;
  }

  private $fields;
}

$obj = new ex;
$obj->prop = array(4 => 'pear');

$obj->prop[5] = 'apple';
?>
--8<--

as expected it will work exactly the same as the first example. but the
output "setting property prop" is not shown when the $obj->prop[5] which
I find a little strange.

but now if I do not store the values in the object as an array but store
them as something else like a serialized string it will not work. eg.

--8<--
<?php

class ex {
  public function __get($prop) {
    echo "getting property $prop\n";
    return unserialize($this->fields[$prop]);
  }

  public function __set($prop, $value) {
    echo "setting property $prop\n";
    $this->fields[$prop] = serialize($value);
  }

  private $fields;
}

$obj = new ex;
$obj->prop = array(4 => 'pear');

$obj->prop[5] = 'apple';
?>
--8<--

Now this example will not work. Could someone please help me understand
why. I have a funny feeling that the __set() is not being called, and
something in the php5 overload code is guessing what should happen and
doing it.

I am not on the php-general mail list so any replies can you please send
it directly to me.

Thanks to anyone that can solve this for me.
Gordon.

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to