I'm trying to write a method for a class Queue
that inverts the whole Queue
. After running the program, it gives the follow problem:
Cannot use object of type Queue as array on line
echo($i.". ".$this->kolejka[$i-1]."<br>");
Apparently when he is trying to use printOut
method again on the inverted Queue
. Please help!
Please don't laugh (too hard) as I tried many things to make this work and I'm lost.
Here is the whole code:
<?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();
?>