Reply to problems with overloading in php 5.

Your name:

Reply:


Posted by Gordon Heydon on 07/29/05 04:22

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.

[Back to original message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация