php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #47567 Problem "Overloading" arrays with __set.
Submitted: 2009-03-04 23:55 UTC Modified: 2009-03-21 01:00 UTC
From: vyk2rr at gmail dot com Assigned: dmitry (profile)
Status: No Feedback Package: Scripting Engine problem
PHP Version: 5.2.9 OS: Ubuntu 8.10
Private report: No CVE-ID: None
Have you experienced this issue?
Rate the importance of this bug to you:

 [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

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2009-03-10 10:35 UTC] jani@php.net
Dmitry, you closed bug #33941 with comment "this is not fixable". Can you explain why it isn't? :)
 [2009-03-13 15:05 UTC] dmitry@php.net
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]; }
 [2009-03-21 01:00 UTC] php-bugs at lists dot php dot net
No feedback was provided for this bug for over a week, so it is
being suspended automatically. If you are able to provide the
information that was originally requested, please do so and change
the status of the bug back to "Open".
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Wed Apr 24 03:01:29 2024 UTC