php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #67899 __set() not firing when array is updated
Submitted: 2014-08-24 12:05 UTC Modified: 2014-09-01 20:18 UTC
From: spikeon at gmail dot com Assigned:
Status: Not a bug Package: Class/Object related
PHP Version: 5.5.16 OS: Mac
Private report: No CVE-ID: None
 [2014-08-24 12:05 UTC] spikeon at gmail dot com
Description:
------------
__set() doesn't fire if the variable is an array and a new value is pushed to that array

---
From manual page: http://www.php.net/language.oop5.magic
---


Test script:
---------------
class Foo(){
    private $info = [];
    function __set($k, $v){
        $this->info[$k] = $v;
    }
    function __get($k){
        return $this->info[$k] ?: null;
    }
}

$bar = new Foo();
$bar->foo = [];
$bar->foo[] = "foo1";
var_dump($bar->foo); // returns Array()

Expected result:
----------------
Upon update of the array, the array should be re-submitted to the __set() method.  If this would cause issues, perhaps a new magic method could be created to handle changes of this nature, eg: __update() or __change().


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2014-09-01 20:17 UTC] daverandom@php.net
This cannot work and does not make sense.

__set() is used for replacing the whole value. The code sample causes __get() to fire, returning the property, but it does not (and cannot) return a reference to the value and as such the underlying data store cannot be modified. The engine actually triggers an E_NOTICE to warn you of this limitation.

This limitation can be worked around by setting the magic $foo property value to an object that implements ArrayAccess, as this would mean that __get() would return the same instance and the modification would be made to that instance.
 [2014-09-01 20:18 UTC] daverandom@php.net
-Status: Open +Status: Not a bug
 [2014-09-01 20:18 UTC] daverandom@php.net
Not a bug as explained above.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Mar 28 08:01:28 2024 UTC