假设我们有一个索引类
class Index{
/* indexing fields */
public $id ;
public $word;
/* Constructor */
public function __construct($id, $word)
{
$this->id = $id;
$this->word = $word;
}
}到目前一切尚好?好的。
现在,假设我们必须实现一个字典,将单词映射到它们的同义词。
/* 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]);这一产出如下:
array(3) {
[0]=>
string(4) "evil"
[1]=>
string(4) "mean"
[2]=>
string(3) "php"
}如果想给我们的单词再加一个同义词,那该怎么做呢?我试过这个:
/* Adding one more synonym */
$synonymsDictionary->offsetGet($word)[] = "unlucky";
echo var_dump($synonymsDictionary[$word]);然而,这一产出与上面的产出相同:
array(3) {
[0]=>
string(4) "evil"
[1]=>
string(4) "mean"
[2]=>
string(3) "php"
}我遗漏了什么?
发布于 2018-02-28 08:33:21
将所有同义词保存为数组而不是单个字符串:
$synonymsDictionary[$word] = array("evil", "mean", "php");所以现在您可以添加新的项$synonymsDictionary[$word][] = 'unlucky'
此外,offsetGet只返回数据,而不是引用数据。因此,您以后更改的内容永远不会被分配回同义词词典。
所以你需要这个:
$data = $sd->offsetGet($word);
$data[] = 'unlucky';
$sd->offsetSet($word, $data);https://stackoverflow.com/questions/49025024
复制相似问题