我正在尝试为一个Queue
反转整个Queue
. 运行程序后,出现以下问题:
无法在线使用 Queue 类型的对象作为数组
echo($i.". ".$this->kolejka[$i-1]."<br>");
显然,当他再次尝试使用printOut
方法时,就倒了Queue
。请帮忙!
请不要笑(笑得太厉害),因为我尝试了很多方法来完成这项工作,但我迷路了。
这是整个代码:
<?php
class Queue
{
private $Queue = array(); //Init
public function clear() //Clears the Queue
{
$this->Queue = array();
}
public function isMember($item) //Returns True if element is in the Queue
{
foreach($this->Queue as $x)
{
if($item === $x)
{
return true;
}
}
return false;
}
public function remove() //Removes first element
{
return array_shift($this->Queue);
}
public function add($item) //Adds element to the end
{
$this->Queue[] = $item;
}
public function first() //Returns the first element
{
return current($this->Queue);
}
public function printOut() //Writes down in order all the elements
{
for($i=1;$i < count($this->Queue)+1;$i++)
{
echo($i.". ".$this->Queue[$i-1]."<br>");
}
}
public function length() //Returnts length
{
return count($this->Queue);
}
public function invert() //Reverts the Queue
{
$newQueue = new Queue();
for ($i = $this->length() - 1;$i>=0;$i--)
{
$newQueue->add($this->first());
$this->remove();
}
$this->Queue = $newQueue;
}
}
$kolej = new Queue();
$kolej->add("Apple");
$kolej->add("Orange");
$kolej->add("Banana");
$kolej->add("Mandarin");
$kolej->add("Raspberry");
echo $kolej->first()."<br>";
$kolej->remove();
echo $kolej->first()."<br>";
echo $kolej->isMember("Apple")."<br>";
echo $kolej->isMember("Orange")."<br>";
$kolej->printOut();
echo "Currently Queue is of length ".$kolej->length()."<br>";
$kolej->invert();
$kolej->printOut();
?>