1

I guess it is has something to do with ArrayAccess because $this and the objects in $this->products[$key] do implement ArrayAccess. However there is no magic __get or __set anywhere.

var_dump($this->products[$key]['selected_options'][$option_key]);
// Output: string(7) "Größe:S"

$this->products[$key]['selected_options'][$option_key] = "test";

var_dump($this->products[$key]['selected_options'][$option_key]);
// Output: string(7) "Größe:S"

Does someone have any idea what is wrong here?

Also note that this does work:

$this->products[$key]['selected_options'] = array($option_key => "test");
// Output: string(4) "test"

ArrayAccess for Products same for $this (Cart) but with $products instead of $data:

class Product implements ArrayAccess
{
    protected $data;

    /* **** ArrayAccess **** */
    public function offsetExists($offset) {
        return isset($this->data[$offset]);
    }

    public function offsetGet($offset) {
        return $this->data[$offset];
    }

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

    public function offsetUnset($offset) {
        unset($this->data[$offset]);
    }
}
PiTheNumber
  • 22,828
  • 17
  • 107
  • 180

3 Answers3

2

You need to return by reference inside offsetGet.

From the manual:

While direct modification triggers a call to ArrayAccess::offsetSet(), indirect modification triggers a call to ArrayAccess::offsetGet(). In that case, the implementation of ArrayAccess::offsetGet() must be able to return by reference, otherwise an E_NOTICE message is raised.

Note, however, that this only works with PHP >= 5.3.4

Community
  • 1
  • 1
phant0m
  • 16,595
  • 5
  • 50
  • 82
1

You might be trying to change an immutable property.

How is $this->products defined? What is its visibility? You'll need to look into the scope of the current class and see whether properties can be overwritten after instantiation.

Community
  • 1
  • 1
hohner
  • 11,498
  • 8
  • 49
  • 84
0

Well i ran this:

// INPUT: string(7) "Größe:S"
$products = array();

$key = 1;
$option_key = 1;

$products[$key]['selected_options'][$option_key] = "badgers";

$products[$key]['selected_options'][$option_key] = "xxx";

var_dump($products[$key]['selected_options'][$option_key]);

And the output was:

string(3) "xxx"

So more code is needed i think?

Paul
  • 276
  • 1
  • 14