Saturday, 11 January 2025

Indirect modification of overloaded property has no effect

<?php
error_reporting(E_ALL);

class PropertyTest
{
    /**  Location for overloaded data.  */
    private $data = array();


    public function __set($name, $value)
    {
        $this->data[$name] = $value;
    }

    public function __get($name)
    {
        if (array_key_exists($name, $this->data)) {
            return $this->data[$name];
        } else {
            throw new Exception($name . " not found");
        }
    }
}

$obj = new PropertyTest();
$obj->goods = ["a", "b"];

//the line below will throw notice
//Indirect modification of overloaded property PropertyTest::$goods has no effect
$obj->goods[] = "c";

//still got ["a", "b"]
var_dump($obj->goods);

To fix the error, replace the last two lines of codes with the below.

$obj->goods= array_merge($obj->goods, ['c']);

//got ["a", "b", "c"]
var_dump($obj->goods);

Here is another example

$obj = new PropertyTest();
$obj->test=["a"=>2];
var_dump($obj->test);
//will throw the notice and will not change value
$obj->test['a'] =3;
//the result is the same as what we get from the last dump
var_dump($obj->test);

To make it work as expected

$obj = new PropertyTest();
$obj->test=["a"=>2];
var_dump($obj->test);

$ans = $obj->test;
$ans['a'] = 3;
$obj->test = $ans;
var_dump($obj->test)

No comments:

Post a Comment