|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2009-03-04 23:55 UTC] vyk2rr at gmail dot com
Description:
------------
I can't add values to an array using __set($k, $v){...}
This look like this other bug http://bugs.php.net/bug.php?id=39449 but is not the same
This is the same bug http://bugs.php.net/bug.php?id=33941 but is closed :S
So I'm researching in the manual (http://www.php.net/manual/en/language.oop5.overloading.php), but there is nothing about it
Reproduce code:
---------------
<?php
class test {
private $vars = array();
public function __set($k, $v) { $this->vars[$k] = $v; }
public function showAll(){
echo "<pre>";
foreach($this->vars as $k=>$v){
echo "$k: ";
print_r($v); echo "<br />";
}
echo "</pre>";
}
}
$t = new test();
$t->a = 'one';
$t->b = 'two';
$t->c = array('one','two');
$t->c[] = 'three';
$t->c[] = 'four';
$t->d = array( );
$t->d[] = 'one';
$t->e = 'three';
$t->showAll();
?>
Expected result:
----------------
a: one
b: two
c: Array
(
[0] => one
[1] => two
[2] => three
[3] => four
)
d: Array
(
[0] => one
)
e: three
Actual result:
--------------
a: one
b: two
c: Array
(
[0] => one
[1] => two
)
d: Array
(
)
e: three
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Fri Nov 07 13:00:01 2025 UTC |
In this example the __set() handler isn't called for $t->c[] = ...; statements. Note that __set() is called only when you assign to overloaded property itself but not to its part. In case you are trying to access a part of a property __get() handler is called. Especially for this case you can use __get() handler returning by reference. Addition of the following method makes script work in the way you expected. public function &__get($k) { return $this->vars[$k]; }