Suppose we have an Index class:
JavaScript
x
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.
JavaScript
/* 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:
JavaScript
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:
JavaScript
/* Adding one more synonym */
$synonymsDictionary->offsetGet($word)[] = "unlucky";
echo var_dump($synonymsDictionary[$word]);
This, however, outputs the same output as the one above :
JavaScript
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:
JavaScript
$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:
JavaScript
$data = $sd->offsetGet($word);
$data[] = 'unlucky';
$sd->offsetSet($word, $data);