Skip to content
Advertisement

How to dynamically add elements to the array value of an SplObjectStorage object

Suppose we have an Index class:

class Index{
    /* indexing fields */
    public $id ;
    public $word;
    
    /* Constructor */
    public function __construct($id, $word)
    {
        $this->id = $id;
        $this->word = $word;
    }
}

So far so good? ok.

Now, imagine we have to implement a dictionary that maps words to their synonyms.

/* Create SplObjectStorage object. should work as data-structure that 
     resembles a HashMap or Dictionary */
     $synonymsDictionary = new SplObjectStorage(); 

/* Create a word index object, and add it to synonyms dictionary */
    $word = new Index(1,"bad");
    $synonymsDictionary[$word] = array("evil", "mean", "php");

/* print it out */
    echo var_dump($synonymsDictionary[$word]);

This outputs:

array(3) {
 [0]=>
   string(4) "evil"
 [1]=>
   string(4) "mean"
 [2]=>
   string(3) "php"
 }

If wanna add one more synonym to our word, how to go about that? I tried this:

/* Adding one more synonym */
   $synonymsDictionary->offsetGet($word)[] = "unlucky"; 
   echo var_dump($synonymsDictionary[$word]);

This, however, outputs the same output as the one above :

     array(3) {
        [0]=>
   string(4) "evil"
        [1]=>
   string(4) "mean"
        [2]=>
   string(3) "php"
 }

What am I missing? ????

Advertisement

Answer

Save all synonyms as array instead of single string:

$synonymsDictionary[$word] = array("evil", "mean", "php");

So now you can add new item $synonymsDictionary[$word][] = 'unlucky'


Also offsetGet only returns data, not reference to data. So what you later change is never assigned back to synonyms dictionary.

So you need this:

$data = $sd->offsetGet($word);
$data[] = 'unlucky';
$sd->offsetSet($word, $data);
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement