这是一段代码。已经实现了前缀树(trie)
<?php
class KTrie implements Serializable
{
function __construct()
{
$this->root = new KTrieNode('');
}
function addWord($word)
{
$wordArray = str_split($word);
$this->root->addSuffix($wordArray);
}
function hasWord($word)
{
$wordArray = str_split($word);
return $this->root->hasSuffix($wordArray);
}
function printStructure()
{
$this->root->printStructure(0);
}
function printWords()
{
$this->root->printWords('');
}
public function serialize() {
return serialize($this->data);
}
public function unserialize($data) {
$this->data = unserialize($data);
}
}
class KTrieNode
{
function __construct($s){ $this->value = $s; }
function addSuffix($suffixArray)
{
if(!empty($suffixArray))
{
$firstChar = $suffixArray[0];
$remnant = array_slice($suffixArray, 1);
$childNode = $this->getChild($firstChar);
if($childNode === FALSE)
{
$childNode = $this->addChild($firstChar);
}
$childNode->addSuffix($remnant);
}
else
{
$this->finishesWord = TRUE;
}
}
function hasSuffix($suffixArray)
{
if(!empty($suffixArray))
{
$firstChar = $suffixArray[0];
$childNode = $this->getChild($firstChar);
if($childNode == FALSE)
{
return FALSE;
}
else
{
$remnant = array_slice($suffixArray, 1);
return $childNode->hasSuffix($remnant);
}
}
else
{
return TRUE;
}
}
function getChild($childString)
{
if(is_array($this->children))
{
foreach ($this->children as $child)
{
if($child->value === $childString)
{
return $child;
}
}
}
return FALSE;
}
function addChild($childString)
{
if(is_array($this->children))
{
foreach($this->children as $child)
{
if($child->value === $childString)
{
return $child;
}
}
}
$child = new KTrieNode($childString);
$this->children[] = $child;
return $child;
}
function printStructure($level)
{
for($i=0; $i<$level; $i++)
{
echo ".";
}
echo $this->value.'<br/>';
if(is_array($this->children))
{
foreach($this->children as $child)
{
$child->printStructure($level + 1);
}
}
}
function printWords($prefix)
{
if($this->finishesWord)
{
echo $prefix.$this->value.'<br/>';
}
if(is_array($this->children))
{
foreach($this->children as $child)
{
$child->printWords($prefix.$this->value);
}
}
}
}
$trie = new KTrie();
$trie->addWord('123123123123'); // key 1
$trie->addWord('123123455644'); // key 2
$trie->addWord('12312354443'); // key 3
$trie->addWord('123123547787'); // key 3
/* and so on , for every item you add */
//$trie->printWords();
$ser=serialize($trie);
$newobj = unserialize($ser);
var_dump($newobj->printWords());
?>
使用var_dump($newobj->printWords());
时出现的错误是 在非对象上调用成员函数printWords()
为什么?因为在反序列化变量$ser
后我应该得到类Ktrie的一个对象,因此函数printWords()
理想情况下应该正常运行
非常感谢任何帮助
谢谢!